Home > Back-end >  How to build many different packages with CMake
How to build many different packages with CMake

Time:04-10

I'm trying to put together a CMake project where I have different packages that I need to build. This is my desired structure:

package1
  src
    file.cpp
  test
    file_test.cpp
package2
  src
    file2.cpp
  test
    file2_test.cpp
CMakeLists.txt
main.cpp // this will be removed later

This is my current CMakeLists.txt file:

cmake_minimum_required(VERSION 3.10)

# set the project name
project(cppApp)

# specify the C   standard
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD_REQUIRED True)

include_directories(${PROJECT_SOURCE_DIR})

# add the executable
add_executable(cppApp main.cpp ./package1/src/file.cpp ./package2/src/file2.cpp)

So the question is firstly, is a library considered a package in CMake? This question comes from someone who have done a lot of Java where I would typically call that a package and not a library. But does it in CMake?

Also, how do I in CMake include all files in the "packages" to be built instead of hard coding in the files as an executable? If I create many .cpp/.h files I want to automate this as much as possible.

I have seen that some other projects use a CMakeLists.txt file inside each "package", is this ideal? And is this good practice?

If you have a better suggestion according to some standard I should use to structure my project I would like to know a good one as well.

CodePudding user response:

So the question is firstly, is a library considered a package in CMake? This question comes from someone who have done a lot of Java where I would typically call that a package and not a library. But does it in CMake?

Your definition of package in Java is not quite accurate. Package is just a mean to organize classes in Java in namespace manner. It could be classes of a separate library, but nothing prevents you from using different packages within the same project. It has nothing to do with CMake packages, where each package is actually a whole separate project.

I have seen that some other projects use a CMakeLists.txt file inside each "package", is this ideal? And is this good practice?

CMakeLists.txt files in subderictories merely define new subset of rules for those directories. In order to make your CMake project respect those rules, you add such directory with add_subdirectory. It's not neccessarily a separate library, you can make subset of rules for parts of a single project, and it's usually a good idea to do that if some files are really that different.

CMake have something called add_library(lib) and is those kinds of directories considered a library?

add_library creates so-called CMake target, just like add_executable. The targets can be linked with each other with use of target_link_libraries, and that will indeed be considered a library in terms of C .

  • Related