gpt4 book ai didi

#ifndef 可以忽略方法或变量重复吗?

转载 作者:行者123 更新时间:2023-12-04 12:08:31 26 4
gpt4 key购买 nike

考虑代码。

#ifndef FOO_H
#define FOO_H
//Code
#endif

代码可以是以下情况

// Case 1: 
#define foo 0
// Case 2:
void foo_method(){};
// Case 3:
int foo;

foo.h 包含在许多 C 文件中。当我只编译case 1没有错误时,其他case会抛出重复错误。

当编译时 foo.h 没有连接到 C 文件时为什么会这样?

最佳答案

关于案例2:
你应该只声明函数签名,而不是主体。它与预处理器命令无关。

在头文件中(仅声明)

#if <Condition>
void foo();
#endif

在C文件中

#if <Condition>
void foo(){
//body
}

#endif

关于案例3:
和case 2类似,如果变量是extern,则需要在头文件中声明,否则不需要在头文件中声明。如果它们声明为extern,它们也需要在没有extern关键字的C文件中声明:

在头文件中:

#if <Condition>
extern int bar;
#endif

在C文件中:

#if <Condition>
int bar;
#endif

关于#ifndef 可以忽略方法或变量重复吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32868712/

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