Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
729 views
in Technique[技术] by (71.8m points)

multiple definition of namespace variable, C++ compilation

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...