Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
310 views
in Technique[技术] by (71.8m points)

assembly - how to reference global variable from C that was defined in .asm file in visual studio

I have a .asm file that defines variable foo

file.asm:

.data
foo DWORD 0

.code
{ ... }

I want to reference foo outside of file.asm in main.c , This what i have tried:

main.c

extern int foo;

int main()
{
    foo++;
}

However this causes a linker error: LNK2001 unresolved external symbol foo , how can i reference it from main.c ?

UPDATE:

I have also tried using the PUBLIC directive:

file.asm:

.data
PUBLIC foo
foo DWORD 0

This causes same linker error LNK2001

question from:https://stackoverflow.com/questions/65895957/how-to-reference-global-variable-from-c-that-was-defined-in-asm-file-in-visual

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

MSVC uses underscores at the beginning of symbol names, and apparently uses PUBLIC to export a symbol (otherwise labels are internal, like static variables in C). Try

.data
PUBLIC _foo
_foo DWORD 0

This is essentially what MSVC itself does, see https://godbolt.org/z/Phb4Pv


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...