Manjunath Gumma
Manjunath Gumma

Reputation: 21

Run make install command in cmake from another cmake file

We have multiple libraries in different folder, The main application needs to build those libraries in other folders and install them to output folder and then the main application needs to link to libraries to build executable.

I am able to build the libraries present in other folders using add_subdirectory() in a loop, but I am not able to install them to output folder by main cmake file. Could anyone help me out on this.

Upvotes: 2

Views: 2092

Answers (1)

Dmitry
Dmitry

Reputation: 3143

The main application needs to build those libraries in other folders and install them to output folder and then the main application needs to link to libraries to build executable.

It is not necessary in CMake to install libraries in order to link to them. You can build the libraries and have your main executable link to them without installing the libraries. When you need to install your application as a whole, you can install libraries along with the executable if needed i.e. if the libraries are shared ones and not static ones.

One example of how you can organize things: assume you have the following structure in your project:

CMakeLists.txt  # root of project
  |
  |--lib 
  |   |--CMakeLists.txt  # library subproject
  |
  |--app
      |--CMakeLists.txt  # app subproject

Then your root CMakeLists.txt can look like this:

project(MyProject)

add_subdirectory(lib)
add_subdirectory(app)

The lib subproject's CMakeLists.txt can look like this:

project(MyLib)

set(SOURCES <...>) # specify library's sources
add_library(${PROJECT_NAME} ${SOURCES})

set(MyLib ${PROJECT_NAME} CACHE INTERNAL "")

The last line in the snippet above is aimed to make MyLib variable available everywhere within the project. I found this trick here and used it successfully in my projects. Maybe there are better options here, if anyone knows them, feel free to suggest.

The app's CMakeLists.txt can then look like this:

project(MyApp)

set(SOURCES <...>) # specify app's sources
add_executable(${PROJECT_NAME} ${SOURCES})
target_link_libraries(${PROJECT_NAME} ${MyLib})

I haven't covered the installation here but it's actually straightforward: if your libraries are static ones, you only need to install the executable using install TARGETS. If your libraries are shared ones, you need to install them along with the executable.

Upvotes: 0

Related Questions