Automatically use the directory as the project nam

2019-04-04 07:08发布

I'm fairly new at using CMake to manage my build system, so if I'm being stupid and this is a bad idea, please let me know.

I'd like to be able to set up my cmakelists.txt file so that when I do

project( ... )

the name of the directory becomes the project name automatically. I want to do this because I find it convenient to be able to copy the entire directory of one project as the starting point of another. However, though I always rename the directory to something meaningful, I often forget to change the project(name) line of the cmakelists.txt file, and then I end up with multiple projects open in my build environment with the same name, which gets confusing.

Ideally, if there are spaces in the directory name they'd be replaced by underscores.

Can CMake do this? And is it a bad idea for some reason I'm not seeing?

标签: cmake
2条回答
干净又极端
2楼-- · 2019-04-04 07:48

I think CMAKE_CURRENT_LIST_DIR more suitable for this case

get_filename_component(ProjectId ${CMAKE_CURRENT_LIST_DIR} NAME)
string(REPLACE " " "_" ProjectId ${ProjectId})
project(${ProjectId} C CXX)
查看更多
欢心
3楼-- · 2019-04-04 07:54

You can achieve this by adding the following to the start of your CMakeLists.txt:

get_filename_component(ProjectId ${CMAKE_CURRENT_SOURCE_DIR} NAME)
string(REPLACE " " "_" ProjectId ${ProjectId})
project(${ProjectId})

I don't see a problem with doing this for throwaway projects, although I guess production projects would normally have a predefined name which would be set explicitly in the project command.

When you mention that you "copy the entire directory of one project as the starting point of another", I assume you don't include the build tree when you copy? CMake isn't really able to handle the build tree being moved.

查看更多
登录 后发表回答