用CLion 刷题如何创建多个main函数

tech2026-08-07  0

用CLion 刷题如何创建多个main函数

让Clion像codeblocks一样可以建多个main()

1:手动修改CmakeList.txt

add_executable(MAIN main.cpp) add_executable(a a.cpp) add_executable(b b.cpp)

2:在CMake文件中编写自动生成程序

在Cmake文件中编写程序,自动生成编译后的文件名!

基础版

只会遍历根目录下的cpp文件,不会遍历根目录下的二级目录。

遍历项目根目录下所有的 .cpp 文件 file (GLOB files *.cpp) foreach (file ${files}) string(REGEX REPLACE ".+/(.+)\\..*" "\\1" exe ${file}) add_executable (${exe} ${file}) message (\ \ \ \ --\ src/${exe}.cpp\ will\ be\ compiled\ to\ bin/${exe}) endforeach ()

进阶版

就是手动添加访问二级目录的规则,同样要访问三级目录就是再添加一个*//.cpp

# 遍历项目根目录及二级目录下所有的 .cpp 文件 file (GLOB files *.cpp */*cpp) foreach (file ${files}) string(REGEX REPLACE ".+/(.+)\\..*" "\\1" exe ${file}) add_executable (${exe} ${file}) message (\ \ \ \ --\ src/${exe}.cpp\ will\ be\ compiled\ to\ bin/${exe}) endforeach ()

最优版:

官方文档提供一个解决方法GLOB_RECURSE,它会自动遍历工程文件根目录下的所有文件目录。

# 遍历项目根目录下所有的 .cpp 文件 file (GLOB_RECURSE files *.cpp) foreach (file ${files}) string(REGEX REPLACE ".+/(.+)\\..*" "\\1" exe ${file}) add_executable (${exe} ${file}) message (\ \ \ \ --\ src/${exe}.cpp\ will\ be\ compiled\ to\ bin/${exe}) endforeach ()

优点:方便省时

缺点:这种方法要求所有cpp文件命名不重复,不能含有中文,不能含有‘/’等字符!因为它就是直接Copy你的源码文件名的。

最新回复(0)