从命令行覆盖宏 [英] Override macro from the command line

查看:184
本文介绍了从命令行覆盖宏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从命令行重写一个宏。在我的源代码中,有一个像这样的定义:

  #define MY_FOO 1 



我想在编译我的程式时设定这个宏的值:

  g ++ -DMY_FOO = 2 ... 

,宏由源代码重新定义为其旧值1.问题是我不拥有定义宏的源头部分。如果是我自己的代码,我可以简单地写

  #ifndef MY_FOO 
#define MY_FOO 1
#endif

我的问题将会消失。那么有没有办法在命令行中使用g ++指定一个宏,以便源代码无法重新定义它?

解决方案

您可以't。



命令行在任何源文件和头文件之前处理。

如果源文件定义了一个宏,那么它肯定不是定义之前,并将从现在开始获得新值。

更改它的唯一方法是 #undef #define 在稍后的时间再次。如果您有权访问定义后包含的标题,那么您有机会。

I would like to override a macro from the command line. Somewhere in my source, there is a definition like this:

#define MY_FOO 1

What I would like is to set the value of this macro when I compile my program:

g++ -DMY_FOO=2 ...

But then, the macro is redefined by the source code to its old value 1. The problem is that I don't own the part of the source that defines the macro in the first place. If it were my own code, I could simply write

#ifndef MY_FOO
#define MY_FOO 1
#endif

And my problem would be gone. So is there way to specify a macro on the command line using g++ so that the source code cannot redefine it?

解决方案

You can't.

The command line is handled before any source and header files.
If a source file defines a macro, then it must not be defined before, and will get the new value from now on.
The only way to change it, is to #undef and #define it again, at a later point. If you have access to a header that is included after the definition, then you have a chance.

这篇关于从命令行覆盖宏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆