Skip to content

Commit

Permalink
cgen: fix global initializer of fixed array on gcc (#20934)
Browse files Browse the repository at this point in the history
  • Loading branch information
felipensp committed Mar 3, 2024
1 parent ac9b724 commit b638f58
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 2 deletions.
11 changes: 9 additions & 2 deletions vlib/v/gen/c/cgen.v
Expand Up @@ -148,6 +148,7 @@ mut:
inside_const_opt_or_res bool
inside_lambda bool
inside_cinit bool
inside_global_decl bool
inside_interface_deref bool
last_tmp_call_var []string
loop_depth int
Expand Down Expand Up @@ -5975,8 +5976,10 @@ fn (mut g Gen) global_decl(node ast.GlobalDecl) {
// should the global be initialized now, not later in `vinit()`
cinit := node.attrs.contains('cinit')
g.inside_cinit = cinit
g.inside_global_decl = true
defer {
g.inside_cinit = false
g.inside_global_decl = false
}
cextern := node.attrs.contains('c_extern')
should_init := (!g.pref.use_cache && g.pref.build_mode != .build_module)
Expand Down Expand Up @@ -6952,7 +6955,11 @@ fn (mut g Gen) type_default(typ_ ast.Type) string {
.struct_ {
mut has_none_zero := false
info := sym.info as ast.Struct
mut init_str := if info.is_anon { '(${g.typ(typ)}){' } else { '{' }
mut init_str := if info.is_anon && !g.inside_global_decl {
'(${g.typ(typ)}){'
} else {
'{'
}
if sym.language == .v {
for field in info.fields {
field_sym := g.table.sym(field.typ)
Expand Down Expand Up @@ -6988,7 +6995,7 @@ fn (mut g Gen) type_default(typ_ ast.Type) string {
if has_none_zero {
init_str += '}'
if !typ_is_shared_f {
type_name := if info.is_anon {
type_name := if info.is_anon || g.inside_global_decl {
// No name needed for anon structs, C figures it out on its own.
''
} else {
Expand Down
1 change: 1 addition & 0 deletions vlib/v/gen/c/testdata/global_initializer.c.must_have
@@ -0,0 +1 @@
Array_fixed_main__Foo_3 g_test_foo = {{.foo = 0,.bar = {.a = 0,.b = 0,},}, {.foo = 0,.bar = {.a = 0,.b = 0,},}, {.foo = 0,.bar = {.a = 0,.b = 0,},}}; // global4
11 changes: 11 additions & 0 deletions vlib/v/gen/c/testdata/global_initializer.vv
@@ -0,0 +1,11 @@
// vtest vflags: -enable-globals

struct Foo {
foo int
bar struct {
a int
b f64
}
}

__global g_test_foo = [3]Foo{}

0 comments on commit b638f58

Please sign in to comment.