[英]Is it possible to determine or set compiler options from within the source code in gcc?
I have some code that requires a certain gcc compiler option (otherwise it won't compile).我有一些代码需要某个 gcc 编译器选项(否则它不会编译)。 Of course, I can make sure in the makefile that for this particular source file the required option is set.当然,我可以确保在 makefile 中为这个特定的源文件设置了所需的选项。 However, it would much more helpful, if this option could be set for the respective compilation unit (or part of it) from within the source_file.cpp
.但是,如果可以从source_file.cpp
为相应的编译单元(或其一部分)设置此选项,则会更有帮助。
I know that warning messages can be switched on or off using #pragma GCC diagnostic
, but what about the -fsomething
type of options?我知道可以使用#pragma GCC diagnostic
打开或关闭警告消息,但是-fsomething
类型的选项呢? I take it from this question that this is impossible.我从这个问题中认为这是不可能的。
But perhaps there is at least a way to check from within the code whether a certain -f
option is on or not?但也许至少有一种方法可以从代码中检查某个-f
选项是否打开?
Note I'm not interested in finding the compiler flags from the binary, as was asked previously , nor from the command line.注意我对从二进制文件中查找编译器标志不感兴趣, 正如之前所问的那样,也不从命令行中查找。
You can try using some #pragma
.您可以尝试使用一些#pragma
。 See GCC diagnostic pragmas & GCC function specific pragmas .请参阅GCC 诊断编译指示和GCC 功能特定编译指示。
Otherwise, develop your GCC plugin or your MELT extension and have it provide a pragma which sets the appropriate variables or compiler state inside GCC (actually cc1plus
)否则,开发你的 GCC 插件或你的MELT扩展,并让它提供一个 pragma 来在 GCC 中设置适当的变量或编译器状态(实际上是cc1plus
)
In my experience, no.根据我的经验,没有。 This is not the way you go about this.这不是你解决这个问题的方式。 Instead, you put compiler/platform/OS specific code in your source, and wrap it with the appropriate ifdef
statements.相反,您将特定于编译器/平台/操作系统的代码放入源代码中,并使用适当的ifdef
语句对其进行包装。 These include:这些包括:
#ifdef __GNUC__
/*code for GNU C compiler */
#elif _MSC_VER
/*usually has the version number in _MSC_VER*/
/*code specific to MSVC compiler*/
#elif __BORLANDC__
/*code specific to borland compilers*/
#elif __MINGW32__
/*code specific to mingw compilers*/
#endif
Within this, you can have version-specific requirements and code:在此,您可以有特定于版本的要求和代码:
#ifdef __GNUC__
# include <features.h>
# if __GNUC_PREREQ(4,0)
// If gcc_version >= 4.0
# elif __GNUC_PREREQ(3,2)
// If gcc_version >= 3.2
# else
// Else
# endif
#else
// If not gcc
#endif
From there, you have your makefile pass the appropriate compiler flags based on the compiler type, version, etc, and you're all set.从那里,你让你的 makefile 根据编译器类型、版本等传递适当的编译器标志,你就全部设置好了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.