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
849 views
in Technique[技术] by (71.8m points)

linux - C++ shared library undefined reference to `FooClass::SayHello()'

I'm making a C++ Shared Library and when I compile a main exe that uses the library the compiler gives me:

main.cpp:(.text+0x21): undefined reference to `FooClass::SayHello()'
collect2: ld returned 1 exit status

Library code:

fooclass.h

#ifndef __FOOCLASS_H__
#define __FOOCLASS_H__

class FooClass 
{
    public:
        char* SayHello();
};

#endif //__FOOCLASS_H__

fooclass.cpp

#include "fooclass.h"

char* FooClass::SayHello() 
{
    return "Hello Im a Linux Shared Library";
}

Compiling with:

g++ -shared -fPIC fooclass.cpp -o libfoo.so

Main: main.cpp

#include "fooclass.h"
#include <iostream>

using namespace std;

int main(int argc, char const *argv[])
{
    FooClass * fooClass = new FooClass();

    cout<< fooClass->SayHello() << endl;

    return 0;
}

Compiling with:

g++ -I. -L. -lfoo main.cpp -o main

The machine is an Ubuntu Linux 12

Thanks!

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)
g++ -I. -L. -lfoo main.cpp -o main

is the problem. Recent versions of GCC require that you put the object files and libraries in the order that they depend on each other - as a consequential rule of thumb, you have to put the library flags as the last switch for the linker; i. e., write

g++ -I. -L. main.cpp -o main -lfoo

instead.


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

...