我正在编写一个看起来像这样的简单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
我有Mail.cpp
和Spambin.cpp
所需的文件名config.h,所以我有
#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
任何人都可以帮我调试吗?
答案 0 :(得分:41)
您无法在头文件中分配命名空间变量。这样做定义变量而不是声明它们。将它放在一个单独的源文件中,并将其添加到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;
}
答案 1 :(得分:3)
查看Variable definition in header files
您必须将您的变量定义,即值分配放在源文件中,或使用#ifdef保护对其进行保护,以便在包含在单独的源文件中时不会定义两次。
答案 2 :(得分:0)
在头文件中,声明 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