c - 如何处理 C 中的多级包含?

标签 c gcc include c-preprocessor multi-level

我有第二级包括让我悲伤:

Undefined                       first referenced
 symbol                             in file
function2                      /var/tmp//ccAPaWbT.o
ld: fatal: symbol referencing errors. No output written to run
collect2: ld returned 1 exit status

主文件:

#include "functions02.c"
int main(){
int x = funcion2();
}

functions02.c 文件:

#ifndef FUNCTIONS02_C
#define FUNCTIONS02_C
int funcion2();
#if __INCLUDE_LEVEL__ == 0
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include "functions01.c"
int main() {
   return function2();
}
#endif
int function2()
   return function1();
}
#endif

functions01.c 文件:

#ifndef FUNCTIONS01_C
#define FUNCTIONS01_C
int funcion1();
#if __INCLUDE_LEVEL__ == 0
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
int main() {
   return function1();
}
#endif
int function1()
   return 10;
}
#endif

我假设可以使用 __INCLUDE_LEVEL__ 或在 gcc 编译上操作链接来修复此问题,但我找不到 fork 变体。

首先,是否可以在不将函数放入外部头文件中的情况下实现我正在寻找的目标? 其次,正确的做法是什么?

编辑: 我意识到我忘记了向它们添加函数依赖项。也就是说,函数使用的包含不能通过将它们添加到主函数旁边来排除,如果关闭则在排除中扭曲。

最佳答案

是的,可以使用编译时标志(以及在使用 #if 的代码中)包含/排除代码的任何部分,就像您尝试做的那样。

在您的情况下,我假设您没有定义 __INCLUDE_LEVEL__ 标志,因此链接器无法找到 funciton2,因此出现错误。

如果你定义它,你将有三个“main()”:-),它会再次失败。因此,您需要稍微修改一下代码。

此外,#include'ing“C”文件是不可取的,并且在实践中不使用。我假设你只是想尝试和学习,这很好。

关于c - 如何处理 C 中的多级包含?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16493104/

相关文章:

c - 从不兼容的 void * 分配 int*

c++ - 将函数声明为 pure 或 const 对 GCC 的影响(如果不是)

C代码编译失败

c++ - 您是否需要显式包含其他 header 已包含的 header ?

从 linux 主机控制 Jabra 710 USB 扬声器音量

java - 如何使用 C++ dlopen 宏从 C++ 代码而不是 JAVA 加载库

c - 共享内存和 unix domain socket 同步,不重复 shm 内容

c++ - 强制 gcc 不内联函数

ruby-on-rails - 我如何在 Rails 3 的 Controller 中使用 include 来过滤 View 中的结果?

c++ - C++ 中的名称冲突