Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

c++ undefined references with static library

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 generally with this. I bet it's something with symbols. Thanks for any advice, 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:UsersRULERO~1AppDataLocalTemp/ccwM3vLy.o:main.cpp:(.text+0x31): undefined
 reference to `myClass::myClass()'
C:UsersRULERO~1AppDataLocalTemp/ccwM3vLy.o:main.cpp:(.text+0x3c): undefined
 reference to `myClass::function()'
collect2: ld returned 1 exit status
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...