简体   繁体   English

C++ 防止链接器丢弃函数

[英]C++ Prevent linker from discarding functions

I am building a C++ library for android.我正在为 android 构建一个 C++ 库。 I have X.so shared library which ends up in the android app and it's accessed through JNI.我有 X.so 共享库,它最终出现在 android 应用程序中,它是通过 JNI 访问的。 I also have a Ya static library which has few generic functions that is used by X.so.我还有一个 Ya 静态库,它几乎没有 X.so 使用的通用函数。 Ya also has some JNI interface functions as well that should be accessible by the android app. Ya 也有一些 JNI 接口函数,应该可以被 android 应用程序访问。 Currently the problem I'm having is that, after building Ya, I can see all the symbols I need to be exported.目前我遇到的问题是,在构建 Ya 之后,我可以看到所有需要导出的符号。 But after linking that to X.so, linker discards all the JNI interface functions because they are not used internally.但是在将它链接到 X.so 之后,链接器会丢弃所有 JNI 接口函数,因为它们不在内部使用。 I tried the following 2 options without any luck,我尝试了以下 2 个选项,但没有任何运气,

1. 1.

#ifdef __cplusplus
extern "C" {
#endif

JNIEXPORT void JNICALL myImportantFunction(JNIEnv*, jclass);
.
.
.

void* volatile tmp = (void*)&myImportantFunction;
#ifdef __cplusplus
}
#endif

2. 2.

#ifdef __cplusplus
extern "C" {
#endif

JNIEXPORT void __attribute__((used)) JNICALL myImportantFunction(JNIEnv*, jclass);
.
.
.

#ifdef __cplusplus
}
#endif

If there are any clang attributes or hacks which can force the linker not to discard specific functions I need (when I'm building Ya) it would be ideal.如果有任何叮当属性或黑客可以强制链接器不要丢弃我需要的特定功能(当我构建 Ya 时),那将是理想的。 Thank you all for any help in this regards.感谢大家在这方面的任何帮助。

If you want to keep the entire Ya , then -Wl,--whole-archive -lY -Wl,--no-whole-archive is indeed the way to go.如果你想保留整个Ya ,那么-Wl,--whole-archive -lY -Wl,--no-whole-archive确实是要走的路。

If you want to keep only specific symbols from Ya , but let the linker discard other (unused) object files from it, then you need to tell the linker that these functions are used, like so:如果您只想保留Ya特定符号,但让链接器丢弃其他(未使用的)目标文件,那么您需要告诉链接器使用了这些函数,如下所示:

g++ -u myImportantFunction x1.o x2.o ... -lY -shared -o X.so

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM