【发布时间】:2018-01-13 13:47:21
【问题描述】:
我知道在头文件中使用包含保护是为了防止某些东西被定义两次。不过,使用此代码示例完全没问题:
foo.c
#include <stdio.h>
#include <string.h>
#include "bar.h"
int main() {
printf("%d", strlen("Test String"));
somefunc("Some test string...");
return 0;
}
bar.h
#ifndef BAR_H_INCLUDED
#define BAR_H_INCLUDED
void somefunc(char str[]);
#endif
bar.c
#include <stdio.h>
#include <string.h>
#include "bar.h"
void somefunc(char str[]) {
printf("Some string length function: %d", strlen(str));
}
上面的sn-ps是用gcc -Wall foo.c bar.c -o foo编译的,没有报错。但是,<stdio.h> 和 <string.h> 都包含在没有包含保护的情况下。当我将 bar.h 剥离到单个语句 void somefunc(char str[]); 时,仍然没有错误。为什么没有错误?
【问题讨论】:
-
你看过
stdio.h里面了吗? -
我不知道为什么你认为那里应该是一个错误。
-
你怎么知道
stdio.h和string.h不包含保护宏?你检查过你电脑上的文件吗?会出现问题,例如当您有另一个标题包含您的bar.h并且在其他文件中时,您包含bar.h和这个其他标题。 -
对于问题的第二部分:函数后跟
;而不是主体{ }是函数的前向声明。只要真正的函数声明不与前向声明相矛盾,就没有错误。
标签: c macros c-preprocessor header-files include-guards