简要概述:LLVM/Clang是否支持“弱”属性?
我正在学习一些Arduino库源代码(具体来说是HardwareSerial.cpp),并发现了一些有趣的属性weak
,这是我以前从未使用过的:
#if defined(HAVE_HWSERIAL0)
void serialEvent() __attribute__((weak));
bool Serial0_available() __attribute__((weak));
#endif
我发现这很有趣,而且我读到链接器如果没有定义应该将其设置为NULL。
然而,在我使用Clang进行测试时无法使用它。
文件lib.cpp:
#include "lib.h"
#include <stdio.h>
void my_weak_func() __attribute__((weak));
void lib_func() {
printf("lib_func()\n");
if (my_weak_func)
my_weak_func();
}
文件 lib.h:
#ifndef LIB_FUNC
#define LIB_FUNC
void lib_func();
#endif
文件 main.cpp:
#include "lib.h"
#include <stdio.h>
#ifdef DEFINE_WEAK
void my_weak_func() {
printf("my_weak_func()\n");
}
#endif
int main() {
lib_func();
printf("finished\n");
return 0;
}
如果我使用g++ lib.cpp main.cpp -o main -DDEFINE_WEAK
,那么我就能够使用它:
MBA-Anton:Weak_issue asmirnov$ ./main
lib_func()
my_weak_func()
finished
但如果我使用g++ lib.cpp main.cpp -o main
,我将无法链接应用程序:
Undefined symbols for architecture x86_64:
"my_weak_func()", referenced from:
lib_func() in lib-ceb555.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
更详细地了解Clang:
MBA-Anton:Weak_issue asmirnov$ g++ --version
Configured with: --prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include-dir=/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.10.sdk/usr/include/c++/4.2.1
Apple LLVM version 6.1.0 (clang-602.0.53) (based on LLVM 3.6.0svn)
Target: x86_64-apple-darwin14.3.0
Thread model: posix
我该怎么办?LLVM/Clang是否支持weak
属性?
PS. 我已经按照苹果的说明重新编写了lib.cpp,但仍然收到相同的链接器错误:
#include "lib.h"
#include <stdio.h>
extern void my_weak_func() __attribute__((weak_import));
void lib_func() {
printf("lib_func()\n");
if (my_weak_func != NULL)
my_weak_func();
}
xcodebuild -version
)? 以及哪个版本的OSX (sw_vers
)? - Alec