从源文件和头文件的目录中创建CMake项目

时间:2012-11-02 14:32:06

标签: cmake

是否有等同于qmake -project的东西会自动从源文件和头文件目录创建一个CMake项目?

理想情况下,这应该递归地工作。

2 个答案:

答案 0 :(得分:2)

不,但这是一个容易设置的项目:

project(myProject)

enable_language(CXX)

file(GLOB SRC_FILES *.cpp)

include_directories(${PROJECT_SOURCE_DIR})

add_executable(myExe ${SRC_FILES})

假设您正在制作可执行文件。如果您正在创建库,则应使用add_library。如果您的项目内容在srcinclude等子目录中,则只需更改路径。

答案 1 :(得分:0)

(我知道这是很久以前的问题,但无论如何我都会发布我的答案,以供将来参考。)

我认为更好的想法是不要让CMakeLists.txt在每次运行时自动添加带有glob的所有源,而是使用静态源。我想最初的意思是一个脚本,它扫描当前目录(递归地)查找源文件并将它们添加到CMake文件中。这可能会节省大量时间将每个源文件的名称复制到CMake文件。因此:让它自动化吧!

使用以下内容创建名为cmake-project.sh的文件:

#!/bin/bash

# use the first argument as project name
PROJECT_NAME=$1

# find source files, but exclude the build directory
PROJECT_SOURCES=$(find . -iname "*.cpp" -not -path "./build/*") 

# find header files, but exclude the build directory;
# only print the name of the directory; only print unique names
PROJECT_SOURCE_DIR=$(find . -iname "*.h" -not -path "./build/*" \
  -printf "%h\n" | sort -u) 

# The standard content of the CMakeLists.txt can be edited here
cat << EOF > CMakeLists.txt
cmake_minimum_required (VERSION 2.8)

set(PROJ_NAME      $PROJECT_NAME )
set(PROJ_SOURCES   $PROJECT_SOURCES )

project(\${PROJ_NAME})

include_directories(${PROJECT_SOURCE_DIR})

add_executable(\${PROJ_NAME} \${PROJ_SOURCES})
EOF

然后,使用chmod +x cmake-project.sh使文件可执行。现在,您可以在根目录中运行./cmake-project.sh [your_project_name]来自动创建静态(即没有全局)CMakeLists.txt

当然,您必须在必要时调整内容(例如,使用.cc代替.cpp),但您明白了。

相关问题