Request assistance initializing struct instance at global scope
Jacob Carlborg
doob at me.com
Mon Dec 7 13:12:55 UTC 2020
On Monday, 7 December 2020 at 04:13:16 UTC, Andrew Edwards wrote:
> Given:
>
> ===============
> extern(C):
> char*[] hldr;
> enum I = (1<<0);
> struct S { char* ft; char** fm; int f; }
>
> void main(){}
> ===============
>
> // Error Deprecation: static constructor can only be of D
> linkage
> S[] s;
> static this() {
> s = [ S(cast(char*)"c", &hldr[0], I) ];
> }
This is the correct way to do it. The problem is that you have
added `extern(C):` at the top. This means that ever symbol below
will have C linkage. As the error message says, `static this` can
only have D linkage. `static this` is transformed into a function
which is automatically called by the runtime. When you add
`extern(C):` at the top, this function will also get the C
linkage. A simple way to make sure that there are not multiple C
functions with the same name (caused by multiple `static this`,
in the same file or another file) is to mangle the function name
the same way as a D function.
You can either use `extern(C) char*[] hldr` to make only `hldr`
have C linkage. Use `extern(C) {}` to group several symbols which
should have C linkage or rearrange the code so that `static this`
is above `extern(C):`.
--
/Jacob Carlborg
More information about the Digitalmars-d-learn
mailing list