我正在做一个需要以下结构的项目:
2 个 CPP 文件包含类,这些类需要 H 文件 1 中的裸函数。类和裸函数需要 H 文件 2 中的变量。
我可以拆分 CPP 文件,以便它们使用 2 个单独的文件,其中包含所需的 nakes 和变量。但我更喜欢使用这种结构。
好像是编译器跳过了#ifndef命令,我针对这个问题做了测试:
主要内容:
#include <iostream>
//1>CPPFile2.obj : error LNK2005: "bool Test1" (?Test1@@3_NA) already defined in CPPFile1.obj
//1>CPPFile2.obj : error LNK2005: "bool Test2" (?Test2@@3_NA) already defined in CPPFile1.obj
int main()
{
}
CPP文件1:
#include <iostream>
using namespace std;
#include "HFile1.h"
CPP文件2:
#include <iostream>
using namespace std;
#include "HFile2.h"
H文件1:
#include "HFile2.h"
#pragma once
#ifndef Name1
#define Name1
//Use test1, this workes fine
//Use test2, this workes fine
#endif
H文件2:
#pragma once
#ifndef Name2
#define Name2
bool Test1 = false;
bool Test2 = false;
#endif
#ifndef#define #endif 结构怎么可能不能正常工作?
最佳答案
你的问题是第二个标题是定义变量,而不仅仅是声明它们。程序中必须有一个定义,因此编译失败。这与 include guards 无关,因为 include guards 只保护一个翻译单元。在您的情况下,每个 .cpp 文件都包含 header ,因此分别定义了相同的变量。
解决方案是仅声明 header 中的变量并在单个翻译单元中定义它们:
#ifndef Name2
#define Name2
extern bool Test1;
extern bool Test2;
#endif
// single .cpp
bool Test1 = false;
bool Test2 = false;
虽然整个事情都有一些代码味道。您可能想要重新设计您的解决方案。在大多数情况下,使用全局变量并不是一个好的解决方案。
关于c++ - 如何在C++中正确使用#ifndef#define #endif,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12131019/