gcc何时在编译时评估函数? [英] When is gcc evaluating functions at compile time?
问题描述
当我有以下代码时
int main(void) {
printf("%zd\n", strlen("Hello World!"));
return 0;
}
并用-O3
进行编译,strings
将显示字符串"Hello World!".二进制文件缺少它,因为它是在编译时求值的.
and compile it with -O3
, strings
will show that the string "Hello World!" is missing from the binary since it got evaluated at compile time.
如果我改用自己的功能
static inline size_t my_strlen(const char *s) {
const char *tmp = s;
while (*++tmp);
return tmp - s;
}
int main(void) {
printf("%zd\n", my_strlen("Hello World!"));
return 0;
}
使用相同的选项,仍可以在二进制文件中找到该字符串.
with the same options, the string can still be found in the binary.
这是为什么?
推荐答案
因为它是优化符合标准.
在某些系统上,strlen
最终被扩展为GCC编译器已知的_builtin_strlen
.在我的计算机上,/usr/include/x86_64-linux-gnu/bits/string.h
(由<string.h>
包含的间接)具有
On some systems, strlen
is finally expanded to _builtin_strlen
which is known by the GCC compiler. On my machine /usr/include/x86_64-linux-gnu/bits/string.h
(which is indirectly included by <string.h>
) has
# define strlen(str) \
(__extension__ (__builtin_constant_p (str) \
? __builtin_strlen (str) \
: __strlen_g (str)))
实际上是通过GNU glibc
和gcc
So actually is it done by the mix of GNU glibc
and gcc
这篇关于gcc何时在编译时评估函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!