选择在 Makefile 中使用哪个 main()
在 C 项目中,我在多个文件中有一个 main() 函数。当我编译时,出现错误“main 的多个声明”。是否可以在 Makefile 中选择应使用这些 main() 函数之一进行编译? (其他的就被忽略了...)
In a C project, I have a main() function in several files. When I compile I thus have an error "multiple declarations of main". Is it possible to choose in the Makefile which one of those main() functions should be used to compile ? (the other ones would then be ignored...)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用预处理器隐藏它们:
在 file1.c 中:
可以根据需要在任意数量的 C 文件中重复此操作。
然后,Makefile 中的逻辑将正确的 -D 选项传递给编译器,即 -DFILE1_MAIN 包含 file1 中的
main()
,-DFILE2_MAIN 获取 file2.c,等等。该技术在实现例如库模块时也很有用,以包含用于在单个 C 文件中进行测试的可选
main()
。You could hide them using the pre-processor:
In file1.c:
This can be repeated as necessary in any number of C files.
Then have logic in the Makefile that passes the proper -D option to the compiler, i.e. -DFILE1_MAIN to include the
main()
from file1, -DFILE2_MAIN to get file2.c's, and so on.This technique can also be useful when implementing e.g. library modules, to include an optional
main()
for testing in a single C file.您可以简单地为每个
main()
编写一个目标,在其中您将忽略除一个包含main()
的文件之外的所有文件。You could simply write a target for each
main()
, where you would ignore all but one file which containsmain()
.您的源代码中只能有一个
main()
函数。您必须重命名所有其他实例,或者从构建中排除那些包含main()
其他实例的源文件。You only may have one
main()
function in your source. You'll have either to rename all of the other instances, or to exclude those source files that include other instances ofmain()
from the build.