C++ Logo

std-discussion

Advanced search

Re: Global array of objects over multiple files

From: Federico Kircheis <federico_at_[hidden]>
Date: Thu, 17 Oct 2024 19:21:20 +0200
On 17/10/2024 18.34, Thiago Macieira via Std-Discussion wrote:
> On Thursday 17 October 2024 07:58:04 GMT-7 Federico Kircheis via Std-
> Discussion wrote:
>> #define REGISTER_FUN(name) \
>> void name();\
>> [[gnu::used]] constexpr auto CONCAT(helper, __LINE__)
>> [[gnu::section(".tmptests")]] = &name; \
>> void name()
>>
>> REGISTER_FUN(test1){std::puts("test1");}
>> REGISTER_FUN(test2){std::puts("test1");}
>>
>> std::span<test_signature*> get_tests() noexcept {
>> extern test_signature* tests_begin[];
>> extern test_signature* tests_end[];
>
> You don't need the linker scripts if you name your section using identifier-
> only characters (no dot). Then the linker will generate a start and stop
> symbol for you.
>
> https://github.com/opendcdiag/opendcdiag/blob/main/framework/
> sandstone_tests.h#L25-L26
> https://github.com/opendcdiag/opendcdiag/blob/main/framework/
> sandstone_tests.h#L59

Gosh, this is true!

Finally I can have a godbolt example with GCC and clang too

https://godbolt.org/z/1Ted9saGW

>
> Anyway, write a paper that:
> * proposes a suitable C++ syntax for this (I can't think of one)
> * lists a couple of use-cases (they can't be all different because they're all
> arrays)


Yeah, ATM I do not know either what the syntax could be.

It should not be an attribute, because a conforming implementation can
ignore it.
And I guess that the bar for a new keyword is pretty high, .. maybe
register (which by accident is what I've used as macro name in my
previous example) can be reused, as at the moment it has no meaning in c++.


----
#include <cstdio>
#include <cstdint>
#include <span>
using test_signature = void();
void test1(){std::puts("test1");}
register(arrayname) constexpr auto helper1 = &test1;
void test2(){std::puts("test2");}
register(arrayname) constexpr auto helper2 = &test2;
std::span<test_signature*> get_tests() noexcept {
   extern test_signature* arrayname[];
   extern size_t arrayname_size;
   return std::span<test_signature*>(arrayname, arrayname_size);
}
----
> * discusses alternatives. For example, could any of this be done with
>     reflection?
Ok.
I do not think that reflection can iterate over translation units.
> * examines platform support. Are there linkers that can't implement this
>    and aren't under the control of the C++ compiler vendors?
> 
I'm not sure if this is relevant.
Currently the objects are allocated through the linker, but it is an 
implementation detail.
The compiler could create the array through other means, for example 
through a "whole-program-analysis" and even create a constexpr array.

Received on 2024-10-17 17:21:30