How to add source files to another folder

I use cmake to create my C ++ project. Suppose I have the following directories in my source folder

Source |_Dir1 | |_Class.cpp | |_Class.hpp | |_Dir2 |_Main.cpp 

Dir1 has a class with a header and implementation files (Class.cpp and Class.hpp).

Dir2 has a main application that uses a class in Dir1

What is a good way to tell CMakeLists in Dir2 to create an executable file with the Dir1 / Class.cpp file?

EDIT: To be more specific, I want to determine that the source file for Class.cpp should be used in Dir1 CMakeLists.txt, and not in Dir2. Doing this on the other hand seems wrong to me, and it is difficult to use, so if there is a reason why they force me, some clarifications on the topic will be pleasant.

What I am doing now hardcodes the location of the Class.cpp file in Dir2 / CMakeLists.txt, but it just doesn't scale when I have a group of classes interacting together.

+6
source share
1 answer

Suppose you have a single CMakeLists.txt file in the Source directory, you will create two variables using different file() commands

 file(GLOB Dir1_Sources RELATIVE "Dir1" "*.cpp") file(GLOB Dir2_Sources RELATIVE "Dir2" "*.cpp") 

and add both sets generated by the file() commands to the list of target sources:

 add_executable(MyProgram ${Dir1_Sources} ${Dir2_Sources}) 

Alternatively, you can put the CMakeLists.txt file under Dir1 and Dir2 (Main) as follows

 Source | |_ CMakeLists.txt | > project(MyProgram) | > cmake_minimum_required(VERSION 3.8) | > add_subdirectory("Dir1") | > add_subdirectory("Dir2") | |_ Dir1 | |_ CMakeLists.txt | > file(GLOB Sources "*.cpp") | > add_library(Dir1 STATIC ${Sources}) |_ Dir2 |_ CMakeLists.txt > file(GLOB Sources "*.cpp") > add_executable(MyProgram ${Sources}) > target_link_libraries(MyProgram Dir1) 

add subdirectories as additional (static) libraries related to your main purpose.

+13
source

Source: https://habr.com/ru/post/1201581/


All Articles