25

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!

fivunlm
  • 452
  • 1
  • 6
  • 15
  • 2
    Libraries at the end of the compiler command. See http://stackoverflow.com/questions/9966959/noobish-linker-errors-when-compiling-against-glib/9966989#9966989 – hmjd Oct 05 '12 at 14:55
  • 1
    Don't write include guards (or any other names) that contain two underscores or begin with an underscore followed by a capital letter. Those names are reserved to the implementation. (This probably doesn't have anything to do with the right answer to the question) – Pete Becker Oct 05 '12 at 14:56
  • @close voters: I think this question is better than the other one (first of all, the title isn't descriptive, and second of all, the other one has a ton of extraneous junk) – Wug Oct 05 '12 at 15:03

1 Answers1

55
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.

LPs
  • 15,592
  • 8
  • 28
  • 58