命名空间变量的多重定义,C++编译

Glo*_*ior 18 c++

我正在编写一个看起来像这样的简单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
Run Code Online (Sandbox Code Playgroud)

我这是在要求一个文件名的config.h Mail.cppSpambin.cpp,所以我必须 #include "config.h"在这两个Mail.cppSpambin.cpp.config.h看起来像这样:

#ifndef __DEFINE_H__
#define __DEFINE_H__

#include<iostream>

namespace config{
        int On = 1;
        int Off = 0;

        double S = 1.0;
}
#endif
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)

任何人都可以帮我调试吗?

Som*_*ude 43

您无法在头文件中分配命名空间变量.这样做可以定义变量,而不仅仅是声明变量.将它放在一个单独的源文件中,并将其添加到Makefile中,它应该工作.

编辑此外,您必须在头文件中进行声明extern.

所以在头文件中,命名空间应如下所示:

namespace config{
    extern int On;
    extern int Off;

    extern double S;
}
Run Code Online (Sandbox Code Playgroud)

并在源文件中:

namespace config{
    int On = 1;
    int Off = 0;

    double S = 1.0;
}
Run Code Online (Sandbox Code Playgroud)


Ber*_*ard 5

看一下头文件中的变量定义

您必须将变量定义(即值分配)放在源文件中,或者使用 #ifdef 保护来保护它,以免在包含在单独的源文件中时被定义两次。