Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding quotes to argument in C++ preprocessor

I'd like to pass the name of an include file as a compiler argument so that I can modify a large number of configuration parameters. However, my C++ build is via a makefile like process that removes quotes from arguments passed to the compiler and pre-processor. I was hoping to do something equivalent to

#ifndef FILE_ARG // defaults #else #include "FILE_ARG" #endif 

with my command line including -DFILE_ARG=foo.h. This of course doesn't work since the preprocessor doesn't translate FILE_ARG.

I've tried

#define QUOTE(x) #x #include QUOTE(FILE_ARG) 

which doesn't work for the same reason.

For scripting reasons, I'd rather do this on the command line than go in and edit an include line in the appropriate routine. Is there any way?

like image 354
Jonathan Zingman Avatar asked Jul 12 '11 21:07

Jonathan Zingman


People also ask

What is the use of preprocessor in C programming?

All other uses of the preprocessor involve processing #define'd constants or macros. Typically, constants and macros are written in ALL CAPS to indicate they are special (as we will see). The #include directive tells the preprocessor to grab the text of a file and place it directly into the current file.

What are command line arguments in C++?

These values are called command line arguments and many times they are important for your program especially when you want to control your program from outside instead of hard coding those values inside the code.

What happens if no arguments are supplied in the command line?

If no arguments are supplied, argc will be one, and if you pass one argument then argc is set at 2. You pass all the command line arguments separated by a space, but if argument itself has a space then you can pass such arguments by putting them inside double quotes "" or single quotes ''.

Why can't I get the quote command to work?

EDIT: The reason you might not be able to get quoting to work is because the preprocessor works in phases. Additionally I used "gcc (Ubuntu/Linaro 4.5.2-8ubuntu4) 4.5.2", results may vary between compilers. As I said above, I don't have access to the actual command line.


1 Answers

For adding quotes you need this trick:

#define Q(x) #x #define QUOTE(x) Q(x)  #ifdef FILE_ARG #include QUOTE(FILE_ARG) #endif 
like image 57
Karoly Horvath Avatar answered Sep 21 '22 22:09

Karoly Horvath