gpt4 book ai didi

c++ - 代码守卫失败

转载 作者:太空宇宙 更新时间:2023-11-03 10:34:28 25 4
gpt4 key购买 nike

获取这些文件:

啊啊

#ifndef A_H
#define A_H

char EL[] = "el";
#endif

a.cpp

#include "a.h"

b.h

#ifndef B_H
#define B_H

#include "a.h"

#endif

b.cpp

#include "b.h"

主要.cpp

#include "b.h"
#include "a.h"

int main() { }

这只是一个例子,但我确实遇到了这个问题:

g++ -c a.cpp
g++ -c b.cpp
g++ -c main.cpp
g++ -o main main.o a.o b.o


a.o:(.data+0x0): multiple definition of `EL'
main.o:(.data+0x0): first defined here
b.o:(.data+0x0): multiple definition of `EL'
main.o:(.data+0x0): first defined here
collect2: ld returned 1 exit status

为什么以及如何解决?

最佳答案

如果您将定义包含在多个翻译单元中,包含守卫不会保护您避免多次定义一个对象!

作为一个解决方案,永远不要在 header 中定义东西,而只是声明它们:

// header
extern char EL[2];

// TU
#include "header.h"
char EL[2] = "el";

// Other consumer
#include "header.h";
// can now use EL

(当然也有异常(exception);例如,类定义很好(但类成员函数定义不是(但内联函数定义是))——当心。)


我应该补充一点,或者您可以在头文件中使用 static 以使定义对每个 TU 私有(private):

// header
static char EL[] = "EL"; // every TU gets a copy

(不过在 C++0x 中你不能使用静态链接的对象作为模板参数。)

关于c++ - 代码守卫失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6803918/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com