在C中包含头文件

时间:2014-10-13 09:38:18

标签: c include header-files

我正在开发一个项目,如果我可以在运行时包含头文件,它将节省一些编程工作。我谷歌关于它,但都是徒劳的。我的问题是:
我们可以在运行时在C程序中包含头文件吗? 如果是,怎么样?
如果没有,为什么?

3 个答案:

答案 0 :(得分:2)

在C中,源文件只能在编译时读取,因此您的问题的答案是不是。运行时只有可执行的二进制文件,它与源代码头无关。

答案 1 :(得分:1)

不是,不。头文件由编译器购买,以满足编译期间所需的符号。

如果您只想将值无关编译,您可以随时将它们放在运行时读取的配置文件中。

答案 2 :(得分:0)

无法在运行时添加头文件,因为, C程序成为可执行文件的四个阶段如下:

1) Pre-processing
2) Compilation
3) Assembly
4) Linking

和预处理是源代码通过的第一个阶段。在此阶段,完成以下任务:

1) Macro substitution
2) Comments are stripped off
3) **Expansion of the included files**

从中间文件观察显示我们可以通过将参数传递给gcc作为gcc -Wall -save-temps hello.c -o hello:

1) All the macros are expanded in the preprocessing stage.
2) All the comments are stripped off.
3) The third observation is that beside the line ‘#include’ is missing and instead of that we see whole lot of code in its place. So its safe to conclude that stdio.h and header files has been expanded and literally included in our source file.

然后编译代码..

因此需要在编译之前包含头文件。