here are two similar declarations of an object type in C :
struct Obj {
int x;
};
struct ObjC {
int x;
ObjC(int x) : x(x) {};
};
Obj obj1 = {100}
ObjC obj2(200);
using a recent version of gcc (riscv64-unknown-elf-toolchain-10.2.0-2020.12.8
) i find that the variable obj1
is correctly placed in the .data
section.... the variable obj2
, however, is placed in the .bss
section where it is not initialized....
i know there are provisions in GCC to run constructors at startup; but in this case, the initial state of obj2
is known at compile time....
FWIW, my IAR compiler has no problem with this code....
is there some sort of "hint" i need to provide to GCC????
CodePudding user response:
Not marking the constuctor with constexpr
seems to prevent optimizations here. The following type seems to get initialized properly, see godbolt:
struct ObjC2 {
int x;
constexpr ObjC2(int x)
: x(x)
{
}
};
ObjC2 obj3(300);
CodePudding user response:
If you want to increase the chance something gets evaluated at compile time and make the promise to the compiler that the code can be evaluated at compile time then add the constexpr
keyword:
struct Obj {
int x;
};
struct ObjC {
int x;
constexpr ObjC(int x) : x(x) {};
};
But that does not force the compiler to evaluate at compile time. For that mark the variables with constinit
:
constinit Obj obj1 = {100}
constinit ObjC obj2(200);
Note: constinit
does not make the variable const
.