views:

245

answers:

2

hi guys i'm trying to make a static library from a class but when trying to use it i always get errors with undefined references on anything. the way i proceeded was creating the object file like

g++ -c myClass.cpp -o myClass.o

and then packing it with

ar rcs myClass.lib myClass.o

there is something i'm obviously missing generaly with this.. i bet it's something with symbols.. thx for any advices, i know it's most probably something i could find out if reading some tutorial so sorry if bothering with stupid stuff again :)

edit:

myClass.h:

class myClass{
    public:
        myClass();
        void function();
};

myClass.cpp:

#include "myClass.h"

myClass::myClass(){}
void myClass::function(){}

program using the class:

#include "myClass.h"

int main(){
myClass mc;
mc.function();

return 0;
}

finally i compile it like this:

g++ -o main.exe -L. -l myClass main.cpp

the error is just classic:

C:\Users\RULERO~1\AppData\Local\Temp/ccwM3vLy.o:main.cpp:(.text+0x31): undefined
 reference to `myClass::myClass()'
C:\Users\RULERO~1\AppData\Local\Temp/ccwM3vLy.o:main.cpp:(.text+0x3c): undefined
 reference to `myClass::function()'
collect2: ld returned 1 exit status
+1  A: 

Use:

g++ -o main.exe main.cpp myClass.lib 

Using the library path and the -l flag is fraught with problems, but if you must do it, rename your library to libmylib.a and then compile as:

g++ -o main.exe main.cpp -L. -lmylib 

Note also that for portability reasons, it's generally a bad idea to use mixed case in the names of source or output files.

anon
throws the same error :(
stupid_idiot
@stupid_idiot Which you haven't yet provided us with. And *please* change your nick.
anon
yea I heard about recommended names for libraries.. but i already found out the error looks differentely if the library can't be linked.. so i would say that ain't the sollution in this case. and you don't need to hesitate calling me stupid_idiot ;)
stupid_idiot
I always forget the link order matters with g++ - every time :-(
anon
+2  A: 

This is probably a link order problem. When the GNU linker sees a library, it discards all symbols that it doesn't need. In this case, your library appears before your .cpp file, so the library is being discarded before the .cpp file is compiled. Do this:

g++ -o main.exe main.cpp -L. -lmylib

or

g++ -o main.exe main.cpp myClass.lib

The Microsoft linker doesn't consider the ordering of the libraries on the command line.

mch
i'm commiting suicide...
stupid_idiot
Don't. This catches all kinds of developers out. I probably spent a week trying to figure out strange linker problems in a large project that turned out to be this issue.
mch