How to do CMake modules

2019-08-03 05:18发布

问题:

I try to learn c++ with cmake. I have done a project, and cmake runs, it compiles, it works, that is nice, ok. Now I started a new project in which I want to use some classes of the first one. I have tried to read some sourcecode and I have understand that I need to make a module that I can read from both the application. So this will be my repository:

/
/cmake
/modules/Network
/software/sw1
/software/sw2

both the projects sw1 and sw2 depends on the module Netowrk. In the folder cmake there has to be the FindNetwork.cmake file, and in sw1, sw2 and Network there has to be the CMakeList.txt .

But.. I messed up with include_directories and other cmake obscurities..

Can someone point me out to a nice overview how to easily organize a repository with softwares that depend on common modules?

回答1:

This link will provide some examples for you.

In terms of how you are looking at the project/infrastructure then it's best to not confuse things too much. So here is a couple of points to get you started (I hope)

  • In c++ a module is a library (so refer to your Network module as a library)
  • To include a library you need to link it and also make the header files available.

In cmake this is two commands target_link_libraries and include_directories respectively.

With that in mind the project structure could be

/Network/include (api here)
/Network/src
/sw1/src
/sw2/src

with an example base CmakeLists.txt file for you: (place in root dir of project)

cmake_minimum_required(VERSION 2.7) // your choice
project(myproject) // change name 
add_subdirectory(Network)
add_subdirectory(sw1)
add_subdirectory(sw2)

in the Network Directory you would have this

add_library(Network net1.cc net2.cc etc.)

In the sw1 dir

include_dirs(${MYPROJECT_SOURCE_DIR}/Network/include)
link_directories(${MYPROJECT_BINARY_DIR}/Network)
add_executable (sw1prog sw1.cc sw11.cc etc.)
target_link_libraries (sw1prog Network)

In the sw2 dir

include_dirs(${MYPROJECT_SOURCE_DIR}/Network/include)
link_directories(${MYPROJECT_BINARY_DIR}/Network)
add_executable (sw2prog sw2.cc sw21.cc etc.)
target_link_libraries (sw2prog Network)

This is a very simplified version of what you may require, it removes the need for a FindXXModule.cmake file to be created and refers to the library you create implicitly. I think this is the best mechanism for you, if you did want to create a FindXXModule.cmake then I would suggest it's when you actually install your libs to the machine and wish others to be able to find it, either that or have a mechanism for multiple projects to link to each other libraries.

I hope this is a little useful, please bear in mind the cmake site has some examples and cmake --help is your friend.



标签: c++ cmake