CMake: Source file depends on source file - cmake

I am embedding a source file into another source file using inline assembly and .incbin, which is just like I want it. I will not accept the standard objcopy method, which while works is (imho) the lesser method. xxd is also an option, but really only for very small includes. I have a static site builder that takes a lot of resources and packs it into a single program, which is very quick with .incbin.
Unfortunately, adding the JS file to the list of sources is not enough:
ninja explain: output CMakeFiles/jsapp.dir/static_site.c.o older than most recent input static_site.c (1629797306094133842 vs 1629797311521966739)
ninja explain: CMakeFiles/jsapp.dir/static_site.c.o is dirty
ninja explain: jsapp is dirty
[2/2] Linking C executable jsapp
The main C file that embeds the JS is not being rebuilt, but the static site source which is unrelated here is because the timestamp changed.
How can I tell CMake that source.c now depends on some_file.js?

As per #arrowd 's idea:
set_source_files_properties(main.c OBJECT_DEPENDS
${CMAKE_SOURCE_DIR}/my.js
)
Worked beautifully.

Related

Processing assembler files in cmake

I'm trying to create a binary file in cmake which:
- depeneds on some .c source files
- also depeneds on an assembler .s file
Now I have added the .c files normally by setting a variable as a list which contains all .c files in a directory. All good so far.
Now I need to add that assembler file as well as part of my binary directory. I did some research in the mailing archieve of cmake and I saw that with assembler files it's a little different you can't just include them as you do with the c files. You have to sometime preprocess them and include their output as a dependecy to the final binary file. Or so I understood.
The way I tried to do it in my project is something like this:
get assembler file name and path using a get_filename_component command:
in an 'add_custom_command' preprocess the file like this:
COMMAND ${COMPILER_NAME} --preprocess=p ${ASSEMBLER_FILE_NAME} >
${OUT_S_FILE}
Where OUT_S_FILE will be added as a dependency to a target which will be then added as a dependency to the binary file so that it gets created before the binary is created. Now I do not understand the --preprocess=p argument I tried googleing it but to no avail I do not know if it's correct or what it actually does(I have seen it in an example which took care of some assembler files).
set a variable: "ASM_OUT_FILE" to path of the file processed above
create a custom target which depends on this "ASM_OUT_FILE"
Finally add this target as a dependency so it gets created before the binary is created.
I'm sorry I cannot provide more actually example for what I've done but it's work related :D.
The result is "no rule to make target for that assembler file" as if the file was not there but it is(I checked).
Please tell me if possible if there are other things I need to do or if I'm doing something wrong in handling this assembler file. Thank you for reading and I'm sorry if my erxplanation was not so clear!
Edit:
set_source_files_properties(assembly_file.s PROPERTIES COMPILE_FLAGS "-x assembler-with-cpp")

Get build command or all compiler flags that will be used to build a target

Is there a sensible way to get a CMake variable containing the build command or all the compiler flags that CMake will associate with a target?
It doesn't seem practical to try to gather and maintain a list of all properties that could add flags. Besides, CMake must have this info somewhere, since it has to eventually generate a build system.
From the CMake docs it looks like this feature once existed and was provided by calling build_command() but this was replaced:
Note In CMake versions prior to 3.0 this command returned a command
line that directly invokes the native build tool for the current
generator.
Is there a new command that gives the old behavior of build_command()?
Is there a sensible way to get a CMake variable containing the build command or all the compiler flags that CMake will associate with a target?
The answer is no (CMake 3.23 is latest at time of writing), not during the CMake configure step.
In general, such a thing is ill-defined, which is likely why it was removed from CMake and will likely not be re-added. The complications arising from generator expressions, multi-config generators, generators that don't construct command lines (like VS/msbuild), source-file-specific properties, and the simple fact that after the command is called, relevant state might change, all make such efforts quixotic.
Honestly, this is such an odd thing to want at configure time, I wonder if this isn't an XY problem. It's unlikely that one target depends on another in such a way that the entire eventual command line is needed (rather than a particular property) to create it.
I know this is many years later now, but what were you trying to do?
CMake provides many ways post-generation to get information about the compiler command lines.
There's the CMake File API, meant for IDE integration,
The CMAKE_EXPORT_COMPILE_COMMANDS option that creates a Clang-compatible compile_commands.json, and then there's
The CMAKE_<LANG>_COMPILER_LAUNCHER variables that would let you instrument a full command line with a custom script while the build is running.
One of these might be useful. The latter is commonly used with ccache, but can be (ab)used with any arbitrary program as long as the output file is eventually generated.
Note that the latter two only work with the Makefile and Ninja generators.
If you want the final output of how the source files will actually be compiled you will want to look at the generated files. I don't really know a better way currently:
Example:
Here is an example output from Ninja Multi
build\CMakeFiles\impl-Release.ninja
This file will list all of the compile definitions, compiler flags, include directories, object directory, etc.
Under the path "cmake-build-debug/CMakeFiles/" you'll find a folder named as "TopFolderOfYourProject.dir", where the cmake generates all its build system files, including a file "build.make". In this file you can see something like this:
CMakeFiles/somepath/somesourcefile.c
#$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --green --progress-dir=xxx\cmake-build-debug\CMakeFiles --progress-num=$(CMAKE_PROGRESS_1) "Building C object CMakeFiles/somepath/somesourcefile.c.obj"
Besides this, you can find extra info about the flags in the file "flags.make", it contains all extra compiler flags specified by developers.
And in "includes_C.rsp/includes_CXX.rsp" you can see the including path.
Build flags are, actually, associated with source files, because you can have differrent flags for different files. On the other hand, for the most cases these flags are equivalent.
Anyways, to get all build flags for a source file you can use COMPILE_FLAGS property:
get_source_file_property(RESULT file.cpp COMPILE_FLAGS)

Can CMakeLists.txt depend on a file parsed by a function?

I am rather new to CMake, starting off for the first time with a larger project consisting of many subprojects.
For particular reasons (described below for the curious) I already have a set of include files that contain info about the source files needed for each CMake target (lib or exe) – and, for now, I prefer to (re)use these files (reason also described below)
Writing a function to parse these files and add their content as source files to the targets was a surprisingly easy task.
But – now the Problem:
Obviously I want to have each targets CMakeLists.txt depend on the particular include file, that generates the list of source files, so that changes on the include file will be detected as if it were changes to CMakeLists.txt itself, but I simply can’t find any references on how to accomplish that.
N.B.: I found AddFileDependencies but that is for adding dependencies on source files, not the CMakeLists.txt. However, CMake itself can figure out dependencies to included .cmake file somehow, so I figured, it should be possible to do somehow.
Background for the curious:
For this project (quite a number of libraries used by quite a number of executable targets, all organized as subprojects) I was using QMake (without actually using Qt itself) for setting up makefiles. Doing so I was able to use Qt Creator while still being able to generate Visual Studio Solution/Project files automagically. We’re also still in progress of evaluating different IDEs and the choice has not been made yet. But the most important reason to use a generator like QMake / CMake was not being forced to set up the VS files for all these subprojects manually.
Although I needed to trick QMake sometimes to do what I wanted to, things went quite well - even for the VS solution - except for one thing: Visual Studio messes up dependencies on Flex/Bison and other files using custom build rules. It keeps recompiling the Flex/Bison/other files saying „command line changed“ – which I gave up trying to fix.
For this reason I thougt, I’d try CMake as a generator instead, which looks very promising so far – although not having builtin precompiled header support in CMake is somewhat ridiculous these days (off topic, I know).
Since Qt Creators CMake support is by far not as good as the support for QMake projects, I firgured, using the approach of parsing the .pri files containing the source file list would enable me using QMake and CMake side by side – especially since the remaining project settings are rather less complicated than on most open source projects.
There's a nice trick which does exactly what you need. It's based on the idea I found in the git-revision module of #rpavlik see this so question
This is the overall idea:
Create a dummy timestamp file
Add a custom command which touches the timestamp whenever the input .pri file changes
include the timestamp file in your CMakeLists.txt
A possible implementation:
set(input_pri_file <path-to-the-input-pri-file>)
set(timestamp_file ${CMAKE_CURRENT_BINARY_DIR}/timestamp.cmake)
add_custom_command(
OUTPUT ${timestamp_file}
COMMAND ${CMAKE_COMMAND} -E touch ${timestamp_file}
MAIN_DEPENDENCY ${input_pri_file}
VERBATIM
COMMENT "Updating timestamp.cmake"
)
if(NOT EXISTS "${timestamp_file}")
file(WRITE ${timestamp_file} "") # create initial empty file
endif()
include(${timestamp_file})
# create the file list from input_pri_file
....
# use the file list
add_executable(main ${filelist})
Here's what happens when the .pri file changes:
the change triggers the execution of the custom command
which updates the timestamp
because the CMakeLists includes the timestamp it is dependent on it
so updating the timestamp triggers a re-configuration of the CMakeLists.txt
I use the configure_file() if I have some input that should retrigger CMake's configuration process. See e.g. How to make CMake reconfiguration depend on custom file? and configure_file()'s unit test
So in your case it would look something like:
configure_file(SomeInput.pri ${CMAKE_CURRENT_BINARY_DIR}/SomeInput.pri)
Then you use ${CMAKE_CURRENT_BINARY_DIR}/SomeInput.pri to generate the sources. Just make sure you do not add COPYONLY, because then configuration won't retrigger on changes of SomeInput.pri.
EDIT: Alternatively use - a relative new addition - the CMAKE_CONFIGURE_DEPENDS directory property.

How can I control build order in cmake without adding static dependencies?

I'm using OpenGL Loader Generator to generate GL function loading code for my project. It generates gl_loader.h and gl_loader.c. Some of my other source files depend on gl_loader.h, but not all of them, so I need cmake to (re)run glLoadGen if necessary, before compiling the rest of the code, otherwise the build stops with errors because it's trying to compile a file that depends on gl_loader.h before gl_loader.h has been built. I have added the GENERATED property to gl_loader.h/.c but this isn't quite the problem the property is designed to solve and it didn't work.
In this case I can simply add an OBJECT_DEPENDS property to all of my source files, because I will hardly ever need to rerun glLoadGen. But in other situations this would cause too much unnecessary recompilation, such as when several C source and header files are generated by GObjectBuilder (gob2). Manually working out which C files depend on which generated header is impractical.
Another possibility in this case is to run glLoadGen at configure time instead of build time, but that wouldn't be appropriate for the other scenario with gob2.
Is there any other way to tell cmake that it has to run glLoadGen before compiling the other code?
This seems like the ideal scenario for the GENERATED source file property. It basically tells CMake to not worry about the source file not existing at configure time (when CMake runs); it will be available when it's needed at build time (when make/vc/etc. runs).
I'm not familiar with OpenGL or its Loader Generator, but if you use the OUTPUT form of add_custom_command to invoke glLoadGen, the GENERATED property is automatically applied to the output files:
add_custom_command(OUTPUT gl_loader.h gl_loader.c
COMMAND glLoadGen [whatever args are needed]
COMMENT "Generating gl_loader.h and gl_loader.c")
...
add_executable(MyExe ${OtherSources} gl_loader.h gl_loader.c)
WIth this setup, when you build MyExe, the custom command should execute first (if required) producing the appropriate sources (gl_loader.h/.c)

.h generated from .h.in?

There are struct definitions in the .h file that my library creates after I build it.. but I cannot find these in the corresponding .h.in. Can somebody tell me how all this works and where it gets the extra info from?
To be specific: I am building pth, the userspace threading library. It has pth_p.h.in, which doesn't contain the struct definition I am looking for, yet when I build the library, a pth_p.h appears and it has the definition I need.
In fact, I have searched every single file in the library before it is built and cannot find where it is generating the struct definition.
Pth uses GNU Autoconf, Automake, and Libtool. By running ./configure you'll be running a shell script which eventually runs m4 to detect the presence of a whole bunch of different system attributes and make changes to a number of files.
It looks like it boils down to ./configure generating Makefile from Makefile.in and then running something via make that triggers the shtool subcommand scpp:
pth_p.h: $(S)pth_p.h.in
$(SHTOOL) scpp -o pth_p.h -t $(S)pth_p.h.in -Dcpp -Cintern -M '==#==' $(HSRCS)
Obscure link, but here's an shtool-scpp manpage, which describes it as:
This command is an additional ANSI C
source file pre-processor for sharing
cpp(1) code segments, internal
variables and internal functions. The
intention for this comes from writing
libraries in ANSI C. Here a common
shared internal header file is usually
used for sharing information between
the library source files.
The operation is to parse special
constructs in files, generate a few
things out of these constructs and
insert them at position mark in tfile
by writing the output to ofile.
Additionally the files are never
touched or modified. Instead the
constructs are removed later by the
cpp(1) phase of the build process. The
only prerequisite is that every file
has a ``"#include ""ofile"""'' at the
top.
.h.in is probably processed within a configure (generated from configure.ac) script, look out for
AC_CONFIG_FILES([thatfile.h])
It replaces variables of the form #VAR# in the .in file with their values.
Edit: Just noticed if I'm right you should retag your question