Automatically add all files in a folder to a targe

2019-01-02 22:35发布

I am considering switching a cross platform project from separate build management systems in Visual C++, XCode and makefiles to CMake.

One essential feature I need is to add automatically all files in a directory to a target. While this is easy to do with make, it is not easily doable with Visual C++ and XCode (correct me if I am wrong). Is it possible to do it in directly in CMake? How?

Feel free to add any other thing I should be aware of before going to learn CMake, considering that currently the project is mid-sized (8 libraries, 2 executables, 8 test projects and it is depending on about 8 external libs).

2条回答
Bombasti
2楼-- · 2019-01-02 22:57

The answer by Kleist certainly works, but there is an important caveat:

When you write a Makefile manually, you might generate a SRCS variable using a function to select all .cpp and .h files. If a source file is later added, re-running make will include it.

However, CMake (with a command like file(GLOB ...)) will explicitly generate a file list and place it in the auto-generated Makefile. If you have a new source file, you will need to re-generate the Makefile by re-running cmake.

edit: No need to remove the Makefile.

查看更多
唯我独甜
3楼-- · 2019-01-02 23:09

It is possible. E.g. with file(GLOB:

cmake_minimum_required(VERSION 2.8)

file(GLOB helloworld_SRC
    "*.h"
    "*.cpp"
)

add_executable(helloworld ${helloworld_SRC})

Note that this requires manual re-running of cmake if a source file is added or removed, since the generated build system does not know when to ask CMake to regenerate, and doing it at every build would increase the build time.

查看更多
登录 后发表回答