From d9f1e336306a5fcdd3a8a22db17cb325ce96cd06 Mon Sep 17 00:00:00 2001 From: wenxuanjun <41050170+wenxuanjun@users.noreply.github.com> Date: Wed, 3 Dec 2025 20:44:58 +0800 Subject: [PATCH] cgen: allow @[cinit] for const variables (#25881) --- vlib/v/gen/c/consts_and_globals.v | 10 ++++++++++ vlib/v/gen/c/testdata/const_init_cinit.c.must_have | 1 + vlib/v/gen/c/testdata/const_init_cinit.vv | 13 +++++++++++++ 3 files changed, 24 insertions(+) create mode 100644 vlib/v/gen/c/testdata/const_init_cinit.c.must_have create mode 100644 vlib/v/gen/c/testdata/const_init_cinit.vv diff --git a/vlib/v/gen/c/consts_and_globals.v b/vlib/v/gen/c/consts_and_globals.v index c9ca700c2..49d23fa67 100644 --- a/vlib/v/gen/c/consts_and_globals.v +++ b/vlib/v/gen/c/consts_and_globals.v @@ -35,6 +35,16 @@ fn (mut g Gen) const_decl(node ast.ConstDecl) { name := c_name(field.name) const_name := g.c_const_name(field.name) field_expr := field.expr + if field.attrs.contains('cinit') || node.attrs.contains('cinit') { + styp := g.styp(field.typ) + val := g.expr_string(field.expr) + g.global_const_defs[name] = GlobalConstDef{ + mod: field.mod + def: '${g.static_non_parallel}${styp} ${const_name} = ${val};' + dep_names: g.table.dependent_names_in_expr(field.expr) + } + continue + } match field.expr { ast.ArrayInit { elems_are_const := field.expr.exprs.all(g.check_expr_is_const(it)) diff --git a/vlib/v/gen/c/testdata/const_init_cinit.c.must_have b/vlib/v/gen/c/testdata/const_init_cinit.c.must_have new file mode 100644 index 000000000..713eb1a74 --- /dev/null +++ b/vlib/v/gen/c/testdata/const_init_cinit.c.must_have @@ -0,0 +1 @@ +main__Config _const_main__conf = ((main__Config){.id = 123,.name = "test_config",.valid = true,}); \ No newline at end of file diff --git a/vlib/v/gen/c/testdata/const_init_cinit.vv b/vlib/v/gen/c/testdata/const_init_cinit.vv new file mode 100644 index 000000000..d7ef416f0 --- /dev/null +++ b/vlib/v/gen/c/testdata/const_init_cinit.vv @@ -0,0 +1,13 @@ +// vtest vflags: -no-skip-unused +struct Config { + id int + name &char + valid bool +} + +@[cinit] +const conf = Config{ + id: 123 + name: c'test_config' + valid: true +} -- 2.39.5