From 11ef897c1a0a6fb68510e2eb7b1246c42454b43f Mon Sep 17 00:00:00 2001 From: ringabout <43030857+ringabout@users.noreply.github.com> Date: Fri, 17 Jul 2026 17:39:48 +0800 Subject: [PATCH] fixes #26015; Multiple definition error when using codegenDecl regression --- compiler/cgen.nim | 18 ++++++++++++++---- tests/ccgbugs/mcodegendeclglobal.nim | 4 ++++ tests/ccgbugs/tcodegendeclglobal.nim | 12 ++++++++++++ 3 files changed, 30 insertions(+), 4 deletions(-) create mode 100644 tests/ccgbugs/mcodegendeclglobal.nim create mode 100644 tests/ccgbugs/tcodegendeclglobal.nim diff --git a/compiler/cgen.nim b/compiler/cgen.nim index 52c8726485..7339980bc5 100644 --- a/compiler/cgen.nim +++ b/compiler/cgen.nim @@ -1854,10 +1854,20 @@ proc genVarPrototype(m: BModule, n: PNode) = typ = ptrType(typ) if lfDynamicLib in sym.loc.flags: typ = ptrType(typ) - m.s[cfsVars].addVar(m, sym, - name = sym.loc.snippet, - typ = typ, - visibility = vis) + if sfCodegenDecl in sym.flags: + # `codegenDecl` customizes the definition, but a reference from a + # different module still needs a plain declaration. Applying the + # custom format here can turn the declaration into a tentative + # definition (and thus cause duplicate symbols at link time). + m.s[cfsVars].addDeclWithVisibility(vis): + m.s[cfsVars].addVar(kind = Local, + name = sym.loc.snippet, + typ = typ) + else: + m.s[cfsVars].addVar(m, sym, + name = sym.loc.snippet, + typ = typ, + visibility = vis) if m.hcrOn: m.initProc.procSec(cpsLocals).add('\t') m.initProc.procSec(cpsLocals).addAssignment(sym.loc.snippet, diff --git a/tests/ccgbugs/mcodegendeclglobal.nim b/tests/ccgbugs/mcodegendeclglobal.nim new file mode 100644 index 0000000000..1f2ab904f4 --- /dev/null +++ b/tests/ccgbugs/mcodegendeclglobal.nim @@ -0,0 +1,4 @@ +var codegenDeclGlobal* {.codegenDecl: "$# /* custom declaration */ $#".} = 123 + +proc readCodegenDeclGlobal*(): int {.inline.} = + codegenDeclGlobal diff --git a/tests/ccgbugs/tcodegendeclglobal.nim b/tests/ccgbugs/tcodegendeclglobal.nim new file mode 100644 index 0000000000..c8c4f6b7d4 --- /dev/null +++ b/tests/ccgbugs/tcodegendeclglobal.nim @@ -0,0 +1,12 @@ +discard """ + output: ''' +123 +123 +''' + targets: "c cpp" +""" + +import ./mcodegendeclglobal + +echo codegenDeclGlobal +echo readCodegenDeclGlobal()