diff --git a/vlib/v/gen/c/cgen.v b/vlib/v/gen/c/cgen.v index 59e44e1d65e589..f17ee6cf18519b 100644 --- a/vlib/v/gen/c/cgen.v +++ b/vlib/v/gen/c/cgen.v @@ -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 @@ -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) @@ -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) @@ -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 { diff --git a/vlib/v/gen/c/testdata/global_initializer.c.must_have b/vlib/v/gen/c/testdata/global_initializer.c.must_have new file mode 100644 index 00000000000000..8325dde81ff0a1 --- /dev/null +++ b/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 \ No newline at end of file diff --git a/vlib/v/gen/c/testdata/global_initializer.vv b/vlib/v/gen/c/testdata/global_initializer.vv new file mode 100644 index 00000000000000..6f2ad48dc3a8bb --- /dev/null +++ b/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{}