GCC 是否在 return #ifdef 之后排除代码
Does GCC exclude code after a return #ifdef
例如,假设您有以下代码
#define CONDITION
int conditional function();
//...
int foo()
{
#ifdef CONDITION
return conditional_function();
#endif
int value = 0;
//...many more lines
return value;
}
GCC 不会为 return
的 #ifdef
之后的行生成代码吗?还是需要 #else
才能排除该代码?
代码应该是可编译的,任何体面的编译器优化都可能将其作为无法访问的代码删除。
刚刚用 gcc 4.9 编译了这个cc test.c -o test
#include <stdio.h>
#define CONDITION
int test() {
const char* hello = "hello world";
printf("%s\n",hello);
return 2;
}
int main()
{
#ifdef CONDITION
const char* a_test = "hello me";
printf("%s\n",a_test);
return 0;
#endif
volatile const char* hello = "hello musasabi";
printf("%s\n",hello);
return test();
}
然后用 strings test | grep hello
测试生成的二进制文件的内容
"hello me" 和 "hello world" 出现了,但是字符串 "hello musasabi" 不在 test
.
中
例如,假设您有以下代码
#define CONDITION
int conditional function();
//...
int foo()
{
#ifdef CONDITION
return conditional_function();
#endif
int value = 0;
//...many more lines
return value;
}
GCC 不会为 return
的 #ifdef
之后的行生成代码吗?还是需要 #else
才能排除该代码?
代码应该是可编译的,任何体面的编译器优化都可能将其作为无法访问的代码删除。
刚刚用 gcc 4.9 编译了这个cc test.c -o test
#include <stdio.h>
#define CONDITION
int test() {
const char* hello = "hello world";
printf("%s\n",hello);
return 2;
}
int main()
{
#ifdef CONDITION
const char* a_test = "hello me";
printf("%s\n",a_test);
return 0;
#endif
volatile const char* hello = "hello musasabi";
printf("%s\n",hello);
return test();
}
然后用 strings test | grep hello
测试生成的二进制文件的内容
"hello me" 和 "hello world" 出现了,但是字符串 "hello musasabi" 不在 test
.