Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CMake subdirectories dependency

I am very new to CMake. In fact, I am trying it through Kdevelop4 widh C++.

I have the habit of creating subdirs for every namespace I create, even if all the sources must be compiled and linked into a single executable. Well, when i create a directory under kdevelop, it updates CMakeLists.txt with a add_subdirectory command and creates a new CMakeLists.txt under it, but that alone does not add the sources under it to the compilation list.

I have the root CMakeLists.txt as follows:


project(gear2d)

add_executable(gear2d object.cc main.cc)

add_subdirectory(component)

Under component/ I have the sources I want to be compiled and linked to produce the gear2d executables. How can I accomplish that?

CMake FAQ have this entry but if thats the answer I'd rather stay with plain Makefiles.

Is there a way of doing this?

like image 663
Leonardo Avatar asked Apr 12 '11 00:04

Leonardo


People also ask

What does add_ subdirectory do?

Add a subdirectory to the build. Adds a subdirectory to the build. The source_dir specifies the directory in which the source CMakeLists.

What is Add_library in CMake?

add_library(<name> [STATIC | SHARED | MODULE] [EXCLUDE_FROM_ALL] [<source>...]) Adds a library target called <name> to be built from the source files listed in the command invocation. The <name> corresponds to the logical target name and must be globally unique within a project.

What is Cmakelist?

CMake is a meta build system that uses scripts called CMakeLists to generate build files for a specific environment (for example, makefiles on Unix machines). When you create a new CMake project in CLion, a CMakeLists. txt file is automatically generated under the project root.

How do you clean after CMake?

Simply delete the CMakeFiles/ directory inside your build directory. rm -rf CMakeFiles/ cmake --build . This causes CMake to rerun, and build system files are regenerated. Your build will also start from scratch.


1 Answers

Adding a subdirectory does not do much more than specify to CMake that it should enter the directory and look for another CMakeLists.txt there. You still need to create a library with the source files with add_library and link it to your executable with target_link_libraries. Something like the following:

In the subdir CMakeLists.txt

set( component_SOURCES ... ) # Add the source-files for the component here
# Optionally you can use file glob (uncomment the next line)
# file( GLOB component_SOURCES *.cpp )below

add_library( component ${component_SOURCES} )

Top-dir CMakeLists.txt

project( gear2d )
add_subdirectory( component )
add_executable( gear2d object.cc main.cc )
target_link_libraries( gear2d component )
like image 163
André Avatar answered Oct 13 '22 08:10

André