1

I've been grappling with this for about a day now and have yet to find the solution. I'm trying to access a global variable, declared in main.cpp, from an Testing.asm file with both files in the same project using Visual Studio 2019. But I'm getting the following linking error:

    Error LNK2019 unresolved external symbol referenced in function TestRoutine
// main.cpp
        extern "C" int __declspec(dllexport) A; //global variable
        .....
    ########################### Testing.asm #####################
    EXTERN A:QWORD

    .data    

    .code

    main PROC

    main ENDP

    TestRoutine PROC PUBLIC

    MOV EAX, DWORD PTR A 
    RET

    TestRoutine ENDP

    END
Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
Jkf1298
  • 31
  • 2
  • 3
    Using `extern "C"` like that does not define the variable so it does not exist. Try `extern "C" { int A; }` instead. You might also need to use `_A` in your assembly file in case a leading underscore is automatically prepended. Use `dumpbin` to verify symbol name. – Jester Jul 12 '22 at 13:48
  • 3
    Note that name mangling is not applied to variables so you do not even need the `extern "C"`. – Jester Jul 12 '22 at 13:53
  • 1
    @Jester thank you it (extern "C" { int A; }) worked! If you can post your comment as a answer I will accept it. – Jkf1298 Jul 12 '22 at 14:02

1 Answers1

1

I encountered a similar bug in my program. Use extern "C" {int A;} to solve it. BTW you declared A as an int which is a double word (32 bits). And later you declared EXTERN A:QWORD which is 64 bits. At the end, you used MOV EAX, DWORD PTR A. A more straightforward approach is to declare A as a DWORD and remove the DWORD PTR type casting.

Danny Cohen
  • 77
  • 10
  • 1
    You don't need `extern "C"` at all, just `int A;` compiles to the same asm. (Because variable names don't get name-mangled at least in mainstream compilers; only function names do to support overloading.) But yes, you need the C to actually define it, not just have an `extern int A;` reference, unless you want the asm to actually define it with `dd 0` or something. One or the other of the asm and C++ should use `extern` on the variable itself to declare it without reserving space for it. – Peter Cordes Mar 02 '23 at 23:41