I have two static libraries : libfoo and libbar, each one being in its own directory.
libfoo contains a includes/
directory which contains a single file A.h
. It also contains a sources/
directory which contains B.gen
. A custom rule should create a new header B.h
and a new source file B.c
.
libbar contains a includes/
directory which contains a single file C.h
. It also contains a sources/
directory which contains C.c
. This file include the A.h
and the B.h
from libfoo.
The question is : according to these rules, how can I write the CMakeFiles.txt of the two libraries (from my understanding, the tricky part is to have all the libfoo headers in the same directories, but maybe I'm misleading) ?
File hierarchy :
/
libfoo/
includes/
A.h
sources/
A.c
B.gen
CMakeLists.txt
libbar/
includes/
C.h
sources/
C.c
CMakeLists.txt
You should not copy any generated files to the source directory. The separation between a source directory and a build directory is intentional and called out-of-source builds to not pollute the source directory during your build with generated files.
What you need to do in this case is:
Define a custom command which translates your B.gen to a B.h file using add_custom_command. This will generate the B.h inside the CMAKE_CURRENT_BINARY_DIR, which reflects the source directory your CMakeLists.txt is in relative to the project root CMakeLists.txt. It will look something like this:
add_custom_command(OUTPUT B.h COMMAND my-gen B.gen B.h DEPENDS B.gen)
Add the folder where the file was generated to the include directories using the include_directories function. If all of this was done in a single CMakeLists.txt you could use include_directories(${CMAKE_CURRENT_BINARY_DIR})
The CMake dependency parser will now, once it wants to build C.c, analyze its contents and find out that B.h is required for building it. With the add_custom_command you have told it how to create that header and it will invoke your generator.
You should have a look at how out of source builds work in CMake to correctly understand the folder hierarchy.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With