Compile C with subdirectory based on compiler constant

219 views Asked by At

I want to make a program which includes source files and header files from a sub-directory in addition to the main directory. The name of the sub-directory, and parts of the filenames themselves need to be chosen with a compiler constant. Here's an example file tree.

=main.h
=main.c
=anotherfile.h
=anotherfile.c
=A
---= A_file1.h
---= A_file1.c
---= A_file2.h
=B
---= B_file1.h
---= B_file1.c
---= B_file2.h

Every compilation involves main and anotherfile, which reference X_file1 and X_file2 where "X" is chosen at built time or with a constant. So the project can either be built with A files or B files.

So how does one (and what is the "best" way to) implement this? Can one put a reference to a compiler constant in an #include statement? (something like #include X+"/"+"x+"_file1.h) Or is there another way?

I'm very new to C build systems & the preprocessor so apologies if this is a poor question. Search engines have not been much help.

1

There are 1 answers

0
KamilCuk On

how does one implement this?

Either way, I would run to the build system. Configure the build system to compile the file multiple times with different macro definition that points to the file. A crude example:

// main.c
#include IMPL

And then for example with CMake build system:

add_executable(file1 main.c file1.c)
target_compile_definitoins(file1 PUBLIC "IMPL=\"file1.h\"")   
add_executable(file2 main.c file2.c)
target_compile_definitions(file1 PUBLIC "IMPL=\"file2.h\"")
# etc..

Overall, this approach seems wrong and confusing. Strongly consider rewriting your application, so that all files can be compiled together, and all symbols are unique - this will ease up writing and help with IDE to jump to proper function definition, and decrease your head pain.

If you are struggling with providing multiple implementations for the same interface, there is a solution - implement an interface object with function pointers. Then, choose the proper implementation with a constructor or a factory that constructs the object with the virtual interfaces.