Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test whether a CMakeLists.txt is used as a subdirectory [duplicate]

Tags:

cmake

I want to write a CMakeLists that can be used not only as a sub-CMakeLists both also standalone. For example, in the following setup

a
├── b
│   └── CMakeLists.txt
└── CMakeLists.txt

with

$ cat a/CMakeLists.txt
add_subdirectory(b)

However, I'd also like to make a/b/CMakeLists.txt a standalone CMake file that can be used directly by cmake. In particular, a/b/CMakeLists.txt needs to perform a conditional initialization depending on how it is used. Basically something like this:

$ cat a/b/CMakeLists.txt
IF_INCLUDED # dummy
   DO_INIT()
ENDIF
# something else

So, I'm wondering

  1. Is this something that people will do?
  2. Is there a predicate like the aforementioned IF_INCLUDE (again, dummy)?
like image 638
qweruiop Avatar asked Oct 21 '25 03:10

qweruiop


1 Answers

I've seen such setup a few times, so it's certainly something people do. The most common way to phrase such a test is this:

if(CMAKE_SOURCE_DIR STREQUAL CMAKE_CURRENT_SOURCE_DIR)

(or the same with binary directories).

CMAKE_SOURCE_DIR is the directory containing the toplevel CMakeLists.txt (the one on which CMake was originally invoked). CMAKE_CURRENT_SOURCE_DIR is the directory containing the CMakeLists.txt currently being processed. If they are the same, it's guaranteed that the current CMakeList is the top-level one.

like image 127
Angew is no longer proud of SO Avatar answered Oct 24 '25 09:10

Angew is no longer proud of SO



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!