-1

I have written following test program

int proc1();
extern int globalvar;

int func1 ()
{
    return globalvar + 1;
}

int func2()
{
    return proc1()+3;
}

int main()
{
    return 0;
}

As you can see that this program is not doing anything. However, while compiling it, I faced linker error of globalvar and int proc1() despite the facts that these are not going to be referenced from the entry point function main. I faced problem on both Windows(using cl) and Linux(using gcc).

Is there any way to instruct the compiler/linker not to link this unreferenced global variable and function from the entry point (on cl, gcc and clang)?

Exact error message on Windows:

test.obj : error LNK2019: unresolved external symbol "int globalvar" (?globalvar@@3HA) referenced in function "int __cdecl func1(void)" (?func1@@YAHXZ)
test.obj : error LNK2019: unresolved external symbol "int __cdecl proc1(void)" (?proc1@@YAHXZ) referenced in function "int __cdecl func2(void)" (?func2@@YAHXZ)
test.exe : fatal error LNK1120: 2 unresolved externals
doptimusprime
  • 9,115
  • 6
  • 52
  • 90

1 Answers1

1

You can fix this, in gcc, like this:

gcc -ffunction-sections -Wl,--gc-sections test.c

That does two things:

  1. It instructs the compiler to emit each function in its own 'section' in the binary file.

  2. It instructs the linker to discard (garbage collect) sections that are not referenced.

This means that func1 and func2 will be discarded, and therefore there will be not more references to globalvar or proc1.

ams
  • 24,923
  • 4
  • 54
  • 75