3

How can I include a file or another, based on the value of a defined string?

This doesn't work:

#define VAR VALUE_A

#if VAR == "VALUE_A"
    #include "a.h"
#elif VAR == "VALUE_B"
    #include "b.h"
#endif

If it's important, I'm not actually defining VAR, I'm passing it down from the command-line via gcc -D NAME=VALUE.

3 Answers 3

5

The == operator does not compare strings. But you have a couple of other options to configure your includes. In addition to the solutions already mentioned in other answers, I like this one because I think it is quite self-explanatory.

/* Constant identifying the "alpha" library. */
#define LIBRARY_ALPHA 1

/* Constant identifying the "beta" library. */
#define LIBRARY_BETA 2

/* Provide a default library if the user does not select one. */
#ifndef LIBRARY_TO_USE
#define LIBRARY_TO_USE LIBRARY_ALPHA
#endif

/* Include the selected library while handling errors properly. */
#if LIBRARY_TO_USE == LIBRARY_ALPHA
#include <alpha.h>
#elif LIBRARY_TO_USE == LIBRARY_BETA
#define BETA_USE_OPEN_MP 0  /* You can do more stuff than simply include a header if needed. */
#include <beta.h>
#else
#error "Invalid choice for LIBRARY_TO_USE (select LIBRARY_ALPHA or LIBRARY_BETA)"
#endif

Your users can now compile with:

$ cc -DLIBRARY_TO_USE=LIBRARY_BETA whatever.c
Sign up to request clarification or add additional context in comments.

Comments

4

You can use #ifdef or #ifndef for conditional includes.

#ifdef VALUE_A
  #include "a.h"
#endif

#ifdef VALUE_B
  #include "b.h"
#endif

Comments

4

The closest possilibility I can think of is to utilize third form of #include directive (C11 §6.10.2/4), namely define VAR with value, that holds actual header filename:

#define VAR "a.h"

then just use the following:

#include VAR

1 Comment

+1 Why the down-vote? I would have also suggested this myself if @GrzegorzSzpetkowski wouldn't have been faster. This is a very flexible technique that is especially useful to provide hooks in libraries.

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.