作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我正在用 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/
我是一名优秀的程序员,十分优秀!