Automatically use the directory as the project name in CMake

cmake

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?

Best Answer

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.