简体   繁体   中英

cmake to create Makefile with *.cpp rule

I'm just getting started with cmake, I've read some tutorials and got the basic stuff working.

However currently my CMakesList.txt generates a Makefile that has every .cpp explicitly named. That means, whenever I add a new .cpp to my project, I need to rerun cmake, before I can make. While this is not a huge deal, it's still a bit annoying.

Since Makefiles can do something like SOURCES=*.cpp , I thought there's probably a way to tell cmake to generate the Makefile with such a rule!?

I know I can do

cmake_minimum_required(VERSION 2.8)
file(GLOB SRC
    "*.h"
    "*.cpp"
)
add_executable(main ${SRC})

but with that I still have to rerun cmake.

As far as I know, the way to do it is as you have said and the downside is that you have to run cmake every time you add a file.

What I usually do to overcome this is to make a custom target that calls cmake as well. It goes like this

ADD_CUSTOM_TARGET(update
    COMMAND ${CMAKE_COMMAND} ${CMAKE_SOURCE_DIR}
    COMMAND ${CMAKE_COMMAND} --build ${CMAKE_BINARY_DIR} --target all
    COMMENT "Cmake and build"
)

With this you may call make update and it will call cmake first which captures all the files and then starts the build process.

Cmake must be re-runned only if you change your files, becaues CMake compiles the CMakeLists.txt once and then it generates a cached intermediary format that is much more performant. (If you don't add any new file, it is fine bu just running the make command).

Note that CMake cannot use the equivalent feature of MakeFile because otherwise it would f*** up all file dependencies. CMake is not designed to work only with Makefiles as such it only uses a subset of features of target build scripts.

Also if you are already using CMake directly, there's no longer the need to generate makefiles, use CMake, and produce makefiles only if you need to ship your project to clients that have Makefile but not CMake.

You can use this :

file( GLOB_RECURSE
      source_files
      ./*
)

add_executable(main ${source_files})

It is preferable to put all cpp and h files in a src directory then :

file( GLOB_RECURSE
      source_files
      src/*
)

add_executable(main ${source_files})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM