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?
Name of the project given to the project command. This is the name given to the most recently called project() command in the current directory scope or above. To obtain the name of the top level project, see the CMAKE_PROJECT_NAME variable.
CMake will use whatever path the running CMake executable is in. Furthermore, it may get confused if you switch paths between runs without clearing the cache. So what you have to do is simply instead of running cmake <path_to_src> from the command line, run ~/usr/cmake-path/bin/cmake <path_to_src> .
Add a subdirectory to the build. Adds a subdirectory to the build. The source_dir specifies the directory in which the source CMakeLists.
CMAKE_SOURCE_DIR refers to the top-level source directory that contains a CMakeLists. txt , while PROJECT_SOURCE_DIR refers to the source directory of the most recent project() command. They are often the same, but a common workflow when using CMake is to use add_subdirectory to add libraries.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With