gpt4 book ai didi

c - 为什么我的编译守卫不能阻止多重定义包含?

转载 作者:太空狗 更新时间:2023-10-29 16:19:24 24 4
gpt4 key购买 nike

我有一个头文件 x.h,它包含在多个 *.c 源文件中。该头文件定义了一些结构变量。

我在头文件的开头放置了多个包含预防守卫:

#ifndef X_H
#define X_H
...
..
//header file declarations and definitons.


#endif//X_H

在构建时,我收到与多个定义相关的链接器错误。我明白这个问题。

  1. 不会像我一样在头文件的顶部设置多重包含预防保护,防止头文件 x.h 的多重包含,从而避免 x.h 中存在的变量的多重定义?

  2. #pragma once 不适用于这个特定的编译器,那么解决方案是什么?有人发布了 this回答一个类似的问题。它似乎对我不起作用。这个解决方案是如何工作的?

最佳答案

如果链接器报错,则意味着您在 header 中有定义而不仅仅是声明。这是一个错误的例子。

#ifndef X_H
#define X_H

int myFunc()
{
return 42; // Wrong! definition in header.
}

int myVar; // Wrong! definition in header.

#endif

你应该像这样把它分成源文件和头文件:

标题:

#ifndef X_H
#define X_H

extern int myFunc();

extern int myVar;

#endif

C 源代码:

int myFunc()
{
return 42;
}

int myVar;

关于c - 为什么我的编译守卫不能阻止多重定义包含?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/249701/

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