cgccextern

c compiler error with linking


Here is the error I get from the gcc call:

gcc -o rr4 shells2.c graph1.c rng.c;

  Undefined symbols:  
   "_getdisc", referenced from:  
       _main in cckR7zjP.o  
  ld: symbol(s) not found

The "cckR7zjP.o" keeps changing every time I call the compiler. The code for the method is in the file graph1.c; its header file is called graph2.h, and I am importing it to the file with the main method called shells2.c using:

#include "graph2.h"

The method or function definition is:

int getdisc(int i){ return disc[i];}

which attempts to return the ith member of the array disc created by

static int *disc;  

that I already initialized in some other method! I think the problematic call is:

for (iter = 0; iter < n; iter++) {
    if (getdisc(iter) == cln)
        avgbtwn += get_betweenness(iter);
}

This seems like a linker problem I checked with some other questions, and I think I am linking my method properly (and am using the same method elsewhere in the code) but I still can't figure this out.

Edit: So I switched the order of the command in linux to

gcc -o rr4 graph1.c rng.c shells2.c   

as per Soren's suggestion and the function compiled as normal, does anyone know why? Further it seems when i put a trailing line break in the file graph1.c alleviates the problem.


Solution

  • There used to be a issue in the old GCC 2.x compilers/linkers where the linker couldn't resolve linking when the symbols were not group together -- think of it as that the linker would only looks for symbols that is still needed, and it would drop symbols which were unused.

    To most people the problem would manifest itself as a problem of the ordering of libraries (specified with -l or as .a).

    I see from the comments that you use a mac, so it might just be that the mac version of the compiler/linker still has that problem -- anyway since reordering the source files solved the problem, then you certainly have some variation of this bug.

    So possible solutions;

    1. Group all your source files into larger files -- bad solution -- but the linker is less likely to fail with this symptom -- or
    2. Try to compiler all the files to .o first and then link the .o files (using a makefile would usually do this, but may or may not resolve the problem) and possibly combine the .o into a single .a (man ar), or
    3. Change the order of the source files to have the shells2.c last (which worked for you), or
    4. See if upgrading your compiler helps

    Sorry for the long laundry list, but this is clearly just a compiler bug which just need a simple work around.