onqtam onqtam - 1 year ago 95
C++ Question

is there a way to prepend code through the command line of a compiler?

suppose I have this:

int main() { return a; }

and I want to call the compiler and have it compile:

g++ a.cpp --PREPEND-CODE-FLAG="int a = 5;"

is there a way to do this?

Note that I know I can insert a preprocessor definition for
through the command line but I'm looking for a way to prepend real C++ code to the current translation unit.

currently I'm generating a separate header with that code and I'm including it with the
flag for g++/clang

Answer Source

You've tagged this question with several tags pertaining to different C++ implementations, which suggests that you are looking for a cross-platform solution. None exists.

The standard does not specify how a translation unit is passed to the compiler; it never assumes that a translation unit is, for example, a single file. If you are using g++ with a standard shell, you could, for example, compose a translation unit from the execution of several commands:

   echo 'int a = 5';
   echo '#line 1 a.cpp'
   cat a.cpp
} | g++ -Wall -x c++ - 

That will work (with minor variations) with most C++ compilers available on a Unix platform, but is obviously not suitable for a Windows platform. Perhaps other things would be. But whatever solution you use will be individually crafted for the environment in which you are working.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download