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

san*_*ndy 2 c conditional-compilation ifndef

考虑一下代码.

#ifndef FOO_H
#define FOO_H
//Code
#endif
Run Code Online (Sandbox Code Playgroud)

代码可以是以下情况

// Case 1: 
#define foo 0
Run Code Online (Sandbox Code Playgroud)
// Case 2:
void foo_method(){};
Run Code Online (Sandbox Code Playgroud)
// Case 3:
int foo;
Run Code Online (Sandbox Code Playgroud)

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

为什么foo.h在编译时没有连接到C文件除外?

Dav*_*aim 7

关于案例2:
您应该只声​​明函数签名,而不是正文.它与预处理器命令无关.

在头文件中(仅限decleration)

#if <Condition>
void foo();
#endif
Run Code Online (Sandbox Code Playgroud)

在C文件中

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

#endif
Run Code Online (Sandbox Code Playgroud)

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

在头文件中:

#if <Condition>
extern int bar;
#endif
Run Code Online (Sandbox Code Playgroud)

在C文件中:

#if <Condition>
int bar;
#endif
Run Code Online (Sandbox Code Playgroud)