使用clang为gcc生成的.i文件生成.o文件,出现错误

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

代码示例非常简单。

#include <stdio.h>

int main() {
        printf("hello, world");
}
  1. 生成.i文件。

gcc -E test.cpp -o test.cpp.ii

  1. 为 .i 文件生成 .o 文件

clang++ -c test.cpp.ii -o test.cpp.o

显示以下错误消息。

In file included from test.cpp:1:
/usr/include/stdio.h:189:48: error: '__malloc__' attribute takes no arguments
  __attribute__ ((__malloc__)) __attribute__ ((__malloc__ (fclose, 1))) ;
                                               ^
/usr/include/stdio.h:201:49: error: '__malloc__' attribute takes no arguments
   __attribute__ ((__malloc__)) __attribute__ ((__malloc__ (fclose, 1))) ;
                                                ^
/usr/include/stdio.h:223:77: error: use of undeclared identifier '__builtin_free'; did you mean '__builtin_frexp'?
   noexcept (true) __attribute__ ((__malloc__)) __attribute__ ((__malloc__ (__builtin_free, 1)));
                                                                            ^
/usr/include/stdio.h:223:77: note: '__builtin_frexp' declared here
/usr/include/stdio.h:223:65: error: '__malloc__' attribute takes no arguments
   noexcept (true) __attribute__ ((__malloc__)) __attribute__ ((__malloc__ (__builtin_free, 1)));

btw,当使用 gcc 从 .i 文件生成 .o 文件时,一切正常。

  1. attribute ((malloc)) 是 GCC 支持特有的功能?
  2. 既然如此,如何让clang正确生成.o文件
gcc clang llvm
1个回答
0
投票

经过大量调查,我在 glibc 的

stddef.h
中发现了这个:

/* At some point during the gcc 2.96 development the `malloc' attribute
   for functions was introduced.  We don't want to use it unconditionally
   (although this would be possible) since it generates warnings.  */
#if __GNUC_PREREQ (2,96) || __glibc_has_attribute (__malloc__)
# define __attribute_malloc__ __attribute__ ((__malloc__))
#else
# define __attribute_malloc__ /* Ignore */
#endif

如果您看到

stdio.h
,例如:

#undef __attr_dealloc_fclose
#define __attr_dealloc_fclose __attr_dealloc (fclose, 1)

...
...
...

extern FILE *fopen (const char *__restrict __filename,
            const char *__restrict __modes)
  __attribute_malloc__ __attr_dealloc_fclose __wur;

所以,你的例子中的这些属性来自

glibc
,而不是
gcc
,我认为最好不要使用它们。所以我在我的 arch linux 中使用
musl
libc 进行了测试:

pacman -Sy musl

然后

gcc -ansi -pedantic -nostdinc -I /usr/lib/musl/include/ -E test.cpp -o test.cpp.ii
clang++ -c test.cpp.ii -o test.cpp.o

至少对我有用。我希望它对你有用。

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