how to use CMake file (GLOB SRCS *. ) with

2019-04-26 12:46发布

this is my current CMakeLists.txt file

cmake_minimum_required(VERSION 3.3)
set(CMAKE_C_FLAGS " -Wall -g ")
project( bmi )
file( GLOB SRCS *.cpp *.h )
add_executable( bmi ${SRCS}) 

This builds from my source directory, but I have to clean up all the extra files after. My question is how do I build this from a build directory if all my source files are in the same source directory?

thanks

标签: cmake
2条回答
劳资没心,怎么记你
2楼-- · 2019-04-26 13:29

If you really need to use file(GLOB …), this CMakeLists.txt should work :

cmake_minimum_required(VERSION 3.3)
project(bmi)
add_definitions("-Wall" "-g")
include_directories(${PROJECT_SOURCE_DIR})
file(GLOB SRC_FILES ${PROJECT_SOURCE_DIR}/*.cpp)
add_executable(bmi ${SRC_FILES})

In this case you have to launch cmake from your build directory every time you add or delete a source file :

cmake <your_source_dir> -G <your_build_generator>

As Phil reminds, CMake documentation doesn't recommend this use of GLOB. But there are some exceptions. You'll get more information on this post.

If you don't meet those exceptions, you'd rather list your source files than use GLOB :

set(SRC_FILES ${PROJECT_SOURCE_DIR}/main.cpp
              ${PROJECT_SOURCE_DIR}/bmi.cpp
              … )

NB : if you have #include of your .h files in .cpp files, I don't see any reason to put them in add_executable, you just need to specify include directory with include_directories.

查看更多
smile是对你的礼貌
3楼-- · 2019-04-26 13:49

This is not an answer to your question, but I could not format this correctly inside a comment. From the cmake documentation:

Note: 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.

查看更多
登录 后发表回答