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!
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; ie, write
g++ -I. -L. main.cpp -o main -lfoo
instead.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.