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 a
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 -I
flag for g++/clang
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.
$ g++ -DPREPENDED_CODE="int a = 5;" nod.cpp
$ ./a.out
$ echo $?
5
$
where nod.cpp is:
PREPENDED_CODE
int main()
{
return a;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.