Want to warn when i use the same symbol defined two another library when link

Jiang, Guomin 1 Reputation point
2020-07-29T02:06:12.37+00:00

I have below case:

  1. I add below code in testa.c file.

extern unsigned char globaltest;
void a()
{
if (globaltest == 3) {
globaltest = 4;
}
}

  1. Define test lib1.lib and lib2.lib and define globaltest in those lib.
  2. Link testa.obj lib1.lib lib2.lib

I want to encounter warning when execute step 3, but it doesn't happened in fact.

I check the GCC, it have the feature and the error like below:
gcc -o hello hello.c hello2.c
/tmp/ccQThoQE.o:(.data+0x0): multiple definition of `a'
/tmp/ccAAbBRN.o:(.data+0x0): first defined here
collect2: error: ld returned 1 exit status

Hope get your answer, thanks.

Windows API - Win32
Windows API - Win32
A core set of Windows application programming interfaces (APIs) for desktop and server applications. Previously known as Win32 API.
2,492 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Darran Rowe 561 Reputation points
    2020-07-29T17:28:36.817+00:00

    Unfortunately your example in GCC is not the same thing. If you do the exact same thing as you did in Visual Studio then you will get an error.
    14363-2020-07-29.png
    Static libraries work differently to object files though. As documented, external dependencies, which are function or variable names, are found by the linker searching through the list of libraries in the order of those on the command line then those then those added via the the /DEFAULTLIB linker option and then finally default libraries named in object files. What this doesn't explicitly mention is that once it has found a symbol, the linker will stop searching. This means that the linker will only see this as a problem if you use two symbols from two separate libraries and they are in objects that define the same symbols.

    To put this simply, the linker not warning, or caring, is expected behaviour. I would also be surprised if you set up the exact same situation with GCC or LLVM/Clang and the linker complains.

    Also, this is off topic for this tag. You would be better off asking this type of question on the VC General forum.

    0 comments No comments