命名空间变量的多重定义,C++编译
multiple definition of namespace variable, C++ compilation
我正在编写一个简单的Makefile,看起来像这样
CC=gcc
CXX=g++
DEBUG=-g
COMPILER=${CXX}
a.out: main.cpp Mail.o trie.o Spambin.o
${COMPILER} ${DEBUG} main.cpp Mail.o trie.o Re2/obj/so/libre2.so
trie.o: trie.cpp
${COMPILER} ${DEBUG} -c trie.cpp
Mail.o: Mail.cpp
${COMPILER} ${DEBUG} -c Mail.cpp
Spambin.o: Spambin.cpp
${COMPILER} ${DEBUG} -c Spambin.cpp
clean:
rm -f *.o
我有一个文件名config.h,这是Mail.cpp
和Spambin.cpp
所必需的,所以我有 #include "config.h"
Mail.cpp
和Spambin.cpp
。 config.h
看起来像这样:
#ifndef __DEFINE_H__
#define __DEFINE_H__
#include<iostream>
namespace config{
int On = 1;
int Off = 0;
double S = 1.0;
}
#endif
But when I try to compile the code it gives me
Mail.o:(.data+0x8): multiple definition of `config::On'
/tmp/ccgaS6Bh.o:(.data+0x8): first defined here
Mail.o:(.data+0x10): multiple definition of `config::Off'
/tmp/ccgaS6Bh.o:(.data+0x10): first defined here
任何人都可以帮我调试这个吗?
不能在头文件中分配给命名空间变量。这样做可以定义变量,而不仅仅是声明它们。将其放在单独的源文件中,并将其添加到Makefile中,它应该可以工作。
编辑 此外,您必须在头文件中进行声明 extern
.
因此,在头文件中,命名空间应如下所示:
namespace config{
extern int On;
extern int Off;
extern double S;
}
在源文件中:
namespace config{
int On = 1;
int Off = 0;
double S = 1.0;
}
查看头文件中的变量定义
您必须将变量定义(即值赋值(放在源文件中,或者使用 #ifdef 保护它,以免在包含在单独的源文件中时不会定义两次。
在你的头文件中,声明 const 你的 3 个变量。例如,像这样:
#ifndef __DEFINE_H__
#define __DEFINE_H__
#include<iostream>
namespace config{
const int On = 1;
const int Off = 0;
const double S = 1.0;
}
#endif