gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 15:23:58 26 4
gpt4 key购买 nike

我正在用 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com