c++ - 为什么我的 C++ 包含多次定义变量?

标签 c++ c-preprocessor

我知道预处理器命令是头文件的重要组成部分,用于防止变量和类被多次定义。

我一直遇到多次定义变量的问题 - 即使使用预处理器包装器也是如此。这是一个遇到编译器错误的示例项目:

标题:

// TestInclude.h
#ifndef TESTINCLUDE_H_
#define TESTINCLUDE_H_

int myInt;

#endif /*TESTINCLUDE_H_*/

C++:

// TestInclude.cpp
#include <iostream>
#include "IncludeMe.h"
#include "TestInclude.h"

int main( int argc, char* args[] )
{
    std::cin >> myInt;

    IncludeMe thisClass;

    std::cin >> myInt;
}

标题:

// IncludeMe.h
#ifndef INCLUDEME_H_
#define INCLUDEME_H_

class IncludeMe
{
private:
    int privateInt;
public:
    IncludeMe();
};

#endif /*INCLUDEME_H_*/

C++:

// IncludeMe.cpp
#include <iostream>
#include "IncludeMe.h"
#include "TestInclude.h"

IncludeMe::IncludeMe()
{
    std::cout << "myInt: " << myInt;
}

然后我这样编译:

生成文件:

all:
g++ -g -o TestInclude TestInclude.cpp IncludeMe.cpp

我收到以下错误:

/tmp/ccrcNqqO.o: In function `IncludeMe':
/home/quakkels/Projects/c++/TestInclude/IncludeMe.cpp:6: multiple definition of `myInt'
/tmp/ccgo6dVT.o:/home/quakkels/Projects/c++/TestInclude/TestInclude.cpp:7: first defined here
collect2: ld returned 1 exit status
make: *** [all] Error 1

当我在头文件中使用预处理器条件时,为什么会出现此错误?

最佳答案

Include 守卫不会防止多个定义。它们只防止无限递归包含。 (您当然可以在多个翻译单元中包含相同的标题!)

你永远不应该在标题中有对象定义*;只有声明:

header.hpp:

extern int a;

文件.cpp:

#include "header.hpp"

int a = 12;

*) 您可以在头文件中定义类,以及内联函数和类成员函数。

关于c++ - 为什么我的 C++ 包含多次定义变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13282210/

相关文章:

c++ - Eclipse CDT - gdb watch 表达式

c++ - C++中同时的私有(private)和公共(public)继承

c++ - 指针容器

c - 函数的宏驱动条件第一个参数

将 C 宏定义字符串连接到文字字符串

c++ - 基于 for 循环迭代几个元组的范围的简明表示法是什么

java - 在 Android 中使用 OpenCV 非自由模块

c - 如何获取字符串的大小以与预处理器进行比较

c++ - 在代码中修改预处理器宏是一种好的风格吗?

c - 这个定义是什么意思?