How can I set a section to a variable using clang?


    .rel.rodata.func_reg : {
        PROVIDE(func_reg_start = .);
        PROVIDE(func_reg_end = .);


typedef bool (*func_type)();
#define ADD_FUNC(idx, func) \
    static func_type i_##idx##func __attribute__((section(".func_reg." #idx "." #func))) = (func);


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; i += sizeof(func_type)) {
    auto func = *(func_type*)(func_reg_start + i);
    func(); // Expecting execution of test1 / test2 functions at B.cpp / C.cpp


static bool test1() {
    std::cout << "test1" << std::endl;
    return true;
ADD_FUNC(aaa, test1) // Expecting test1() pointer places at ""


static bool test2() {
    std::cout << "test2" << std::endl;
    return true;
ADD_FUNC(aaa, test2) // Expecting test2() pointer places at ""

This implementation works well with g++ but it doesn’t work with clang-15.

It doesn’t give me a build failure using clang but func_size at A.cpp is always 0 and I don’t see pointers at that section.

First I thought it can be a lld problem, but I see “.rel.rodata.func_reg” section is added after text and func_reg_start, func_reg_end symbol is defined from my map file.

Now I am not sure attribute((section(“name”))) works as I expected in llvm…

How should I fix it to make it work?

Thanks for reading, and any advise is welcome!

It also didn’t work when I tried clang with bfd(GNU linker).
# clang++-15 a.cpp b.cpp -fuse-ld=bfd -Wl,-Ta.ld -Wl, -o abc

So now I am doubting more on the section attribute.

Attributes in Clang — Clang 15.0.0 documentation (

Clang reference manual says it supports the section attribute.
Is there an option to enable the section attribute?


__attribute__((used, section(".func_reg." #idx "." #func)))

This works. Added “used” on the macro.