使用 __builtin_va_arg_pack() 时如何构建

问题描述 投票:0回答:1

出于纯粹的教育目的,我尝试使用 “构造函数调用内置函数”https://gcc.gnu.org/onlinedocs/gcc-13.2.0/gcc/Constructing-Calls.html#索引-_005f_005fbuiltin_005fva_005farg_005fpack

我编写了一个示例,其中包含文档中出现的内容:

#include <stdio.h>

extern int myprintf(FILE *f, const char *format, ...);
extern inline __attribute__((__gnu_inline__)) int myprintf(FILE *f, const char *format, ...)
{
    int r = fprintf(f, "myprintf: ");
    if (r < 0)
        return r;
    int s = fprintf(f, format, __builtin_va_arg_pack());
    if (s < 0)
        return s;
    return r + s;
}
int main()
{
    myprintf(stdout, "ciao %d\n", 10);
    return 0;
}

但我无法建造

max@jarvis:~/test$ gcc --version
gcc (Ubuntu 13.2.0-4ubuntu3) 13.2.0
Copyright (C) 2023 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

max@jarvis:~/test$ gcc -std=gnu2x -Wall test1.c -o test1
/usr/bin/ld: /tmp/ccgD1BYT.o: in function `main':
test1.c:(.text+0x27): undefined reference to `myprintf'
collect2: error: ld returned 1 exit status

gcc版本如上所示

我哪里出错了?

gcc built-in function-call
1个回答
0
投票

gcc
的默认优化级别是
-O0
(无)。如果没有,内联不会激活 优化,所以:

$ gcc -std=gnu2x -Wall test1.c -o test1

myprintf
发出常规外部调用,该调用没有定义。

GCC 手册:3.11 控制优化的选项

-fno-内联

除了标有always_inline属性的函数之外,不要内联扩展任何函数。 这是未优化时的默认值

[我的重点]

编译:

$ gcc -O1 -std=gnu2x -Wall test1.c -o test1

或更高版本,程序将按照您的预期进行链接和运行。

进一步参考教派。 3.11 如果你想了解哪些具体的内联选项 在每个优化级别启用。

© www.soinside.com 2019 - 2024. All rights reserved.