0

I have a single cpp file and multiple hpp files. For each hpp file, I want to create an executable using the same cpp file. The header files have different names. Can I do this in CMake?

So I have

source_1.cpp

header_1.hpp header_2.hpp ...

and I want to create

executable_1 executable_2 ...

10
  • 1
    You could use a cascade of macros #ifdef exe1 and pass different macros as preprocessor options, e.g. for GCC it's -D. For -Dexe1 the first header is included and for -Dexe2 the second header is included. Commented Mar 15, 2021 at 12:13
  • Should there be any difference between the different executables? Commented Mar 15, 2021 at 12:14
  • I have 40 different header files and I want to automate it. Each header file is a submission from different people. I am grading their homework Commented Mar 15, 2021 at 12:16
  • You could do this with a script. Commented Mar 15, 2021 at 12:17
  • Why are they "header" files? Why not have them submit the file with cpp suffix? That way you can just compile it. Commented Mar 15, 2021 at 12:19

1 Answer 1

4

The C++ preprocessor can use macros for #include.

That is, you can have something like:

#include HEADER_FILE_TO_INCLUDE

Then when building the source file you could define the macro on the command-line:

g++ -DHEADER_FILE_TO_INCLUDE="\"header_1.hpp\"" source_1.cpp

To do this with CMake you first of all need multiple executable targets, where you specify the same source file for each target.

Then you can use target_compile_definitions to specify the macro and the header file to use.

Something like

add_executable(executable_1 source_1.cpp)
target_compile_definitions(executable_1 HEADER_FILE_TO_INCLUDE="header_1.hpp")

add_executable(executable_2 source_1.cpp)
target_compile_definitions(executable_2 HEADER_FILE_TO_INCLUDE="header_2.hpp")

If all header files are named header_X.hpp, with X just being a sequence number, then you could easily create a loop from 1 to the max value of header file numbers.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.