Reputation: 96
I'm writing a C program, which includes a lot of functionality, some of which will only be required on certain machines by certain people. Some of the functionality requires certain libraries to be installed and without those installed the program will not compile.
What I want is to be able to turn on and off specific bits of functionality, so that it can compile without the extra libraries needed for some bits.
I was wondering if there was an agreed way of doing this in C, and how you might go about it?
My thoughts is that I would use a #define INCLUDE_BOOT_FUNCTIONALITY
, and then inside BootFunctionality.c
I would use a #ifdef INCLUDE_BOOT_FUNCTIONALITY
at the top to only include the code inside it before compilation, if it was defined. I would also then go around to each bit of code where BootFunctionality.c
is used, and wrap it in the #ifdef pre-processor command.
Is this an acceptable way of doing things, or is there a better one?
For context, my code is written in a modular form where each module, for example BootFunctionality.c
runs in its own thread, and is simply started at the start of the program and calls functions available in the Main.c
to talk back. To remove it, all I have to do is remove where it is included in Main.h
and remove the line in Main.c
which starts that thread.
Upvotes: 1
Views: 226
Reputation: 9062
You seem to have a very good structure in your mind. Indeed, it is rather common practice to use #ifdef
s to conditionally remove code at compile time. Just make sure they are robust enough and there isn't some combination of constants that produces an unusable executable.
Keep in mind that the compiler helps a lot, defining for you a bunch of constants so you can use them. This is how you can find what has been defined. And here are the docs. Moreover, each library may introduce some of its own constants. Feel free to use them.
The idea is to automate as much as possible the process. Use the constants defined by libraries to check if they are loaded, constants defined by the compiler to get information about the environment and so on.
Also, too many preprocessor checks can lead to cluttered code. Consider separating, where it makes sense, the code for different conditions.
And finally, think about a build system that would make it easy for the user to select the options he wants and make sure they are well documented.
Upvotes: 3
Reputation: 673
Do it rather opposite way: if platform1_header.h
contains functionality in question for the platform, in source file there should be:
#if defined PLATFORM1
#include "platform1_header.h"
#elif defined PLATFORM2
#include "platform2_header.h"
#endif
And add proper sources into Makefile or any other building script.
Upvotes: 2