Mdp11
Mdp11

Reputation: 572

Organize CMake project the right way

I'm a newbie to CMake and I have several doubts about how to organize my project.

As of now, I have the following structure:

(0)SomeProject
|-- (1)test
|   |
|   |-- CMakeLists.txt
|   `-- tests.cpp
| 
|-- (1)src
|   |-- (2)communication
|   |   |-- CMakeLists.txt
|   |   |-- comm.cpp
|   |   `-- comm.hpp
|   |
|   |-- (2)core
|   |   |-- CMakeLists.txt
|   |   |-- core.cpp
|   |   `-- core.hpp
|   |
|   |-- (2)components
|   |   |-- CMakeLists.txt
|   |   |-- component.hpp
|   |   |
|   |   |-- componentA
|   |   |   |-- compA.cpp
|   |   |   `-- compA.hpp
|   |   `-- componentB
|   |       |-- compB.cpp
|   |       `-- compB.hpp
|   |
|   |-- (2)utils
|   |   |-- CMakeLists.txt
|   |   |-- logging.hpp
|   |   `-- other_util.hpp
|   |
|   |-- (2)exceptions
|   |   |-- CMakeLists.txt
|   |   |-- exceptionA.hpp
|   |   |-- exceptionB.hpp
|   |   `-- exceptionC.hpp
|   |
|   |-- CMakeLists.txt
|   `-- main.cpp
|   
|-- CMakeLists.txt

The root CMake file (level 0) has the following lines:

add_subdirectory(src)
add_subdirectory(test)

And the level 1 CMake files also add all the level 2 subdirectories.

In each level 2 directory, I have the same structure, for example considering the "components" folder:

add_library(compA componentA/compA.cpp componentA.hpp)
target_link_libraries(compA communication exceptions)

add_library(compB componentB/compB.cpp componentB.hpp)
target_link_libraries(compB communication exceptions utils)

And lastly, in the level 1 src CMake file:

add_subdirectory(utils)
add_subdirectory(exceptions)
add_subdirectory(communication)
add_subdirectory(compA)
add_subdirectory(compB)
add_subdirectory(core)

add_executable(project_executable main.cpp)

target_link_libraries(project_executable utils exceptions communication compA compB core)

I'm thinking that this is not the right approach, in particular:

Any suggestion would be greatly appreciated. Thanks in advance.

Upvotes: 4

Views: 1056

Answers (1)

KamilCuk
KamilCuk

Reputation: 140990

the right way

There is no "right way™" or "correct way", there is no bad or wrong. Create a structure that is the best for you for the specific application/use that you are working with.

Is it correct to add everything as a library?

Yes, it gives a nice overview and comfy feeling that you are working with small parts separately.

Is it correct to create a library including only header files?

Yes, INTERFACE libraries are for that.

Any suggestion would be greatly appreciated

Always use PUBLIC/INTERFACE/PRIVATE with target_link_libraries.

Split long lines.

target_link_libraries(project_executable PRIVATE
    utils
    exceptions
    communication
    compA
    compB
    core
)

Upvotes: 1

Related Questions