Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
847 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 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...