简体   繁体   English

有没有一种方法可以通过编译器的命令行添加代码?

[英]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 a through the command line but I'm looking for a way to prepend real C++ code to the current translation unit. 请注意,我知道我可以插入预处理器定义为a通过命令行,但我在寻找一种方式来预先考虑真正的C ++代码,当前转换单元。

currently I'm generating a separate header with that code and I'm including it with the -I flag for g++/clang 目前,我正在使用该代码生成一个单独的标头,并将其包含在g ++ / clang的-I标志中

You've tagged this question with several tags pertaining to different C++ implementations, which suggests that you are looking for a cross-platform solution. 您已经用与不同C ++实现有关的几个标签标记了这个问题,这表明您正在寻找一种跨平台的解决方案。 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: 如果将g++与标准外壳一起使用,则可以例如通过执行以下命令来组成翻译单元:

{
   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. 可以在Unix平台上使用的大多数C ++编译器都可以工作(有微小的变化),但是显然不适合Windows平台。 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: 其中nod.cpp是:

PREPENDED_CODE

int main()
{
    return a;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM