【发布时间】:2015-02-15 14:39:38
【问题描述】:
在 K&R 书 (p59)(编辑:第二版,涵盖 ANSI C)中,建议将较大的项目拆分为多个文件更容易。在每个文件中,像往常一样在顶部包含几个库:例如getop.c 需要 stdio.h,stack.c 和 main.c 也需要。
sn-ps 是这样的:
//main.c
#include <stdio.h>
#include <stdlib.h>
#include "calc.h"
int main(void)
{
//etc
}
//getop.c
#include <stdio.h>
#include <ctype.h>
#include "calc.h"
getop()
{
/*code*/
}
//stack.c
#include <stdio.h>
#include "calc.h"
void push(double val)
{
//code
}
我无法弄清楚在一个项目中多次包含标准库是如何工作的。当然,为了让自定义.c文件能够访问内置函数,我们需要包含#include <header.h>,以便他们知道printf()和getchar()等的存在,但不会这样如果 stdio.h 被包含四次而不是一次(如果所有内容都放在一个文件中),方法会增加最终程序的大小?
K&R 确实指出,将程序拆分为多个文件最终会使维护所有 .h 文件变得更加困难。
我想我真正要问的是编译器如何找出一个库在一个项目中被#include 多次的问题。
我已经阅读了使用 include guards 的内容,但这个实现似乎不需要,因为它们处理的是确保不包含两次相同的代码位,如:
文件“module.h”
#ifndef MODULE_H
#define MODULE_H
struct foo {
int member;
};
#endif /* MODULE_H */
文件“mod2.h”
#include "module.h"
文件“prog.c”
#include "module.h"
#include "mod2.h"
【问题讨论】:
-
您可能想阅读和了解translation units。
标签: c compiler-construction c-preprocessor stdio kernighan-and-ritchie