我知道我一定是在这里做错了什么。
等级.h
#ifndef RANK_H
#define RANK_H
namespace mmi {
int chunk;
void rank(int my_rank);
}
#endif
排名.cpp
#include "rank.h"
namespace mmi {
//do something with chunk
}
主要.cpp
#include "rank.h"
int main() {
mmi::chunk = 1;
}
以及编译的输出;
g++ -g -Wall -std=gnu++11 -c -o main.o main.cpp
g++ -g -Wall -std=gnu++11 -c -o rank.o rank.cpp
mpic++ main.o rank.o -o main
rank.o:(.bss+0x0): multiple definition of `mmi::chunk'
main.o:(.bss+0x0): first defined here
collect2: error: ld returned 1 exit status
Makefile:12: recipe for target 'main' failed
make: *** [main] Error 1
我的理解是头文件被多次包含。但我希望通过使用 #ifndef
来解决这个问题。
所以,请问这是怎么回事?
最佳答案
线
int chunk;
不仅是声明,还是定义。 #include
s .hpp 文件的每个 .cpp 文件最终都会定义它。
改成
extern int chunk;
然后,确保在 .cpp 文件中定义它。
排名.cpp
#include "rank.h"
namespace mmi {
int chunk;
//do something with chunk
}
关于c++ - namespace::variable 的多重定义,即使使用 ifndef,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51435384/