Parsa Noori
Parsa Noori

Reputation: 338

Dependent sibling subdirectories in CMake

My current project has the following structure:

root
 |- parser
 |     |- include    // a directory for headers
 |     |- src        // a directory for sources
 |     |- parser.yy
 |     |- scanner.ll
 |     |- CmakeLists.txt
 |
 |- preprocessor
 |     |- include    // a directory for headers
 |     |- src        // a directory for sources
 |     |- CmakeLists.txt
 |
 |- main.cpp
 |- CMakeLists.txt

Now I want to start generating assembly codes. I have to use staticstack and codegen (are classes which are going to be defined) in the parser.yy and in srcfolder of the parser foler.
I cannot figure out how to do that.
What's the best practice in CMake to do this ?

  1. Should I make subdirectories named semstack and codegen in parser folder ? This doesn't seem correct to me since as a CMake project gets larger the hierarchy will get deeper and if more dependencies are there then it would be a mess.
  2. Should I make these subdirectories in the root ? If then what is the syntax in CMake to use sibling subdirectory ?

Upvotes: 0

Views: 912

Answers (1)

Alex Reinking
Alex Reinking

Reputation: 20026

If then what is the syntax in CMake to use sibling subdirectory ?

There is no special syntax for this since normal (i.e. not IMPORTED) targets are global. If you define a library in one subdirectory, it may be used in any other via target_link_libraries.

For instance:

# parser/CMakeLists.txt

add_library(parser ...)
add_library(proj::parser ALIAS parser)

target_include_directories(
  parser PRIVATE "$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}>")
target_link_libraries(
  parser PRIVATE proj::semstack proj::codegen)

The code for other subdirectories is similar.

# ./CMakeLists.txt

cmake_minimum_required(VERSION 3.22)
project(proj)

add_subdirectory(semstack)
add_subdirectory(codegen)
add_subdirectory(parser)
add_subdirectory(preprocessor)

add_executable(main main.cpp)
target_link_libraries(
  main PRIVATE proj::parser proj::preprocessor)

I create and link to ALIAS targets to avoid a typo in a target name being forwarded to the linker verbatim (names with :: in CMake are always considered targets and this is validated at generation time).

Upvotes: 1

Related Questions