命名空间变量的多重定义,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
$ {编译器} $ {DEBUG} -c Spambin.cpp
clean:
rm -f * .o
我有一个文件名config.h,在 Mail.cpp
和 Spambin.cpp ,所以我在两个
Mail.cpp
#include config.h
>和 Spambin.cpp
。 config.h
看起来像这样:
#ifndef __DEFINE_H__
#定义__DEFINE_H__
#include< iostream>
命名空间配置{
int On = 1;
int Off = 0;
double S = 1.0;
}
#endif
但是当我尝试编译代码时,它给了我
Mail.o :(。data + 0x8):`config :: On'
的多个定义/ tmp / ccgaS6Bh.o :(。data + 0x8):首先在这里定义
Mail.o :(。data + 0x10):`config :: Off'的多个定义
/tmp/ccgaS6Bh.o :(。data + 0x10):首先在这里定义
有人可以帮我调试吗?
您不能在头文件中分配给名称空间变量。这样做定义变量,而不只是声明变量。
编辑并将其放在单独的源文件中,然后应可以使用。
Edit 头文件 extern
中的>声明。
因此,在头文件中,命名空间应类似于
命名空间配置{
extern int On;
extern int关闭;
extern double S;
}
在源文件中:
命名空间配置{
int On = 1;
int Off = 0;
double S = 1.0;
}
I m writing a simple Makefile which looks like this
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
I have a file name config.h which is required in Mail.cpp
and Spambin.cpp
, so I have
#include "config.h"
in both Mail.cpp
and Spambin.cpp
. config.h
looks like this:
#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
Can any one help me debug this?
You can not assign to namespace variables in a header files. Doing that defines the variables instead of just declaring them. Put that in a separate source file and add that to the Makefile and it should work.
Edit Also, you have to make the declarations in the header file extern
.
So in the header file the namespace should look like this:
namespace config{
extern int On;
extern int Off;
extern double S;
}
And in the source file:
namespace config{
int On = 1;
int Off = 0;
double S = 1.0;
}
这篇关于命名空间变量的多重定义,C ++编译的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!