A.ld
SECTIONS
{
.rel.rodata.func_reg : {
PROVIDE(func_reg_start = .);
*(.func_reg.aaa.*)
PROVIDE(func_reg_end = .);
...
}
}
INSERT AFTER .text;
A.hpp
typedef bool (*func_type)();
#define ADD_FUNC(idx, func) \
static func_type i_##idx##func __attribute__((__section__(".func_reg." #idx "." #func))) = (func);
A.cpp
extern uint64_t func_reg_start[];
extern uint64_t func_reg_end[];
uint64_t func_size = func_reg_end - func_reg_start;
for (uint64_t i = 0; i < func_size; j += sizeof(func_type)) {
auto func = *(func_type*)(func_reg_start + i);
func(); // Expecting execution of test() / test2() at B.cpp / C.cpp
}
B.cpp
static bool test() {
std::cout << "test" << std::endl;
return true;
}
ADD_FUNC(aaa, test) // Expecting test() pointer places at ".init_reg.aaa.test"
C.cpp
static bool test2() {
std::cout << "test2" << std::endl;
return true;
}
ADD_FUNC(aaa, test2) // Expecting test() pointer places at ".init_reg.aaa.test2"
我使用链接器脚本实现了此实现,并使用下面的 CMAKE 选项附加了 A.ld。
target_link_options(${BIN_TARGET} PRIVATE -Wl,-T${CMAKE_CURRENT_SOURCE_DIR}/A.ld)
它与 g++ 链接器配合良好,但不适用于 lld 和 Mold。 它不会给我带来构建失败,但 A.cpp 中的 func_size 始终为 0,因此最终什么也不执行。另外,我在地图输出文件的该部分看不到任何内容。 我应该如何修复它才能使其正常工作?
感谢您的阅读!