![](/img/trans.png)
[英]Undefined Reference/ Multiple Definition for namespace extern variable , c++ structuring issue
[英]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保護來保護它,以便在包含在單獨的源文件中時不定義兩次。
your 3 variables. 在頭文件中,聲明 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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.