c - 如何在 C 中条件编译 main()?

标签 c testing compilation program-entry-point

我正在用 C 开发一个小型开源项目,我正在尝试使用 C 的测试框架(该框架是 min_unit)。

我有一个包含原型(prototype)的 foo.h 文件和包含实现的 foo.c 文件。

在我的测试文件 tests.c 中,我有

#include "../test_framework/min_unit.h"
#include "foo.c"

... test cases ...

问题是,因为我在 foo.c 中有一个 main() 函数(我需要编译它),所以我无法编译 tests.c 因为我收到一条错误信息

note: previous definition of ‘main’ was here
int main() {

我的问题是,有没有办法让 foo.c 中的 main() 函数是有条件的,这样当我正在运行 tests.c?必须一遍又一遍地删除和添加 main,这很烦人。

最佳答案

使用条件编译最简单的方法是使用#ifdef 语句。例如,在 foo.c 中你有:

#ifdef NOT_TESTING //if a macro NOT_TESTING was defined
int main() {
    //main function here
}
#endif

test.c 中,您输入:

#ifndef NOT_TESTING //if NOT_TESTING was NOT defined
int main() {
    //main function here
}
#endif

当您想编译foo.c 中的main 函数时,只需将选项-DNOT_TESTING 添加到编译命令即可。如果要编译 test.c 中的 main 函数,请不要添加该选项。

关于c - 如何在 C 中条件编译 main()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29734231/

相关文章:

c++ - Emacs、Cedet 和语义

c - 是否有类似于 printf 的函数,但只返回 C 中格式化字符串的结果?

c - “如何在C中修复错误的加密程序”

unit-testing - 使用枚举的 CakePHP 测试的解决方法?

unit-testing - 什么时候不/在实现前编写测试?

c++ - Visual Studio C++ 复制 obj 文件而不是编译

c - win32 上的 "struct EVENT_LIST"是什么?

javascript - 如何确保在执行脚本之前包含某些库?

C# 从已编译的二进制文件中删除/修改个人文件路径

java - JVM 解释与 JIT 编译。 JVM 不将字节码编译为机器可读吗?