1.简介
本文章的主要目的就是快速搭建个 可以跨windwos平台和linux平台的 c++工程。
主要还是方便linux端工程代码模拟的测试,linux端操作起来比较麻烦。
2.文件内容和搭建方法
1.新建文件夹,将以下两个文件放入
2.如果是windows平台,用cmake 界面搭建工程
3.如果是linux平台,进入文件夹。
执行命令 cmake .
接着执行命令 cmake --build .
文件 CMakeLists.txt
cmake_minimum_required(VERSION 3.10)
project(myProject)
set(CMAKE_CXX_STANDARD 17) # 设置c++版本为c++17
#GLOB_RECURSE 递归地去搜索设定目录下的文件
#cmake可能会在编译过程中生成 CMakeCXXCompilerId.cpp文件 其中就有 main()函数
#由于cmake和main.cpp都在顶级目录中,如果使用了GLOB_RECURSE,则有可能包含了上述cpp
#因此cmake就会报出 main函数重复定义的错误
file(GLOB ALL_FILES
${CMAKE_CURRENT_SOURCE_DIR}/*.cpp
${CMAKE_CURRENT_SOURCE_DIR}/*.h
)
add_executable(myProject ${ALL_FILES})
#链接pthread库,否则在linux下std::thread无法使用
MESSAGE( STATUS "systemType = ${CMAKE_HOST_SYSTEM_NAME}")
if(${CMAKE_HOST_SYSTEM_NAME} MATCHES "Linux")
target_link_libraries (myProject pthread)
endif()
main.cpp
#include <iostream>
#include <vector>
#include <thread>
const int loopTime = 200;
void LoopAdd() {
int res = 0;
for (int i = 0; i < loopTime; i++) {
res += i;
}
}
void Test1Thread() {
std::vector<std::shared_ptr<std::thread>> vecThread;
for (int i = 0; i < loopTime; i++) {
std::shared_ptr<std::thread> th1 = std::make_shared<std::thread>(LoopAdd);
vecThread.push_back(th1);
}
for (auto& tempTh : vecThread) {
tempTh->join();
}
std::cout << "Test1 Thread" << std::endl;
}
int main(){
std::cout << "main" << std::endl;
Test1Thread();
}
运行结果
3.遇到的问题和原理以及解决方法
遇到了main函数重复定义的编译错误
情况如下
原先在cmake中 file用的是 GLOB_RECURSE,而又因为 cmakeList.txt和main.cpp都在根目录。
在linux中直接在根目录 cmake .再 cmake --build.
cmake生成的文件都在根目录下,同时cmake会生成文件CMakeCXXCompilerId.cpp,该文件含有main函数。
GLOB_RECURSE就同时把我定义的文件和CMakeCXXCompilerId.cpp都囊括进去了,这样一来就有了两个main函数,因此报了main函数重复定义的错。
解决方案 是将 GLOB_RECURSE 改为 GLOB
当然以后如果工程庞大了也要注意这种问题,且这个解决方案也需要改进
问题解决方案灵感来源于 链接
c++ - CMake发现不止一个main函数 - IT工具网
c++ - CMake finds more than one main function - Stack Overflow
报错内容
CMakeFiles/my_proj.dir/CMakeFiles/CompilerIdCXX/CMakeCXXCompilerId.cpp.o: In function `main': /media/N/my_proj/build/CMakeFiles/CompilerIdCXX/CMakeCXXCompilerId.cpp:209: multiple definition of `main' CMakeFiles/my_proj.dir/main.cpp.o:/media/N/my_proj/main.cpp:10: first defined here
最佳答案
在您的可执行文件中,您只有 2 个主要函数(通过
MESSAGE(${SRC_FILES})
打印出SRC_FILES
)。一个在main.cpp
中,一个在CMakeCXXCompilerId.cpp
中(这是 CMake 生成的文件,用于测试您的 CXX 编译器是否正常工作)。GLOB_RECURSE
可能会找到这两个文件并将其添加到SRC_FILES
使用 FILE(GLOB ...)很棘手:
We do not recommend using GLOB to collect a list of source files from your source tree. If no CMakeLists.txt file changes when a source is added or removed then the generated build system cannot know when to ask CMake to regenerate.
您应该直接在 CMakeLists.txt 中列出您的源文件和头文件
关于c++ - CMake发现不止一个main函数,我们在Stack Overflow上找到一个类似的问题: c++ - CMake finds more than one main function - Stack Overflow