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
  • 462
  • 1
  • 6
  • 15
  • 3
    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

61
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
  • 16,045
  • 8
  • 30
  • 61
  • 4
    Any idea how we can specify this using qmake? – elyas-bhy Dec 02 '13 at 15:52
  • Good answer! For a long time I don't manually via cmdline build sample project. And right now I spend 1 hour trying to figure what does it mean "undefined reference" during compiling project with gcc-6. The problem was in that you described here! – Konstantin Burlachenko Mar 01 '17 at 19:17
  • 2
    "Recent versions of GCC require..." But *WHY*? It worked before! – Cole Tobin Mar 31 '22 at 15:50
  • This is the important bit: > Recent versions of GCC require that you put the object files and libraries in the order that they depend on each other – masterxilo Jul 24 '22 at 00:44