C++ shared library undefined reference to `FooClass::SayHello()'
Asked Answered
D

1

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!

Divagate answered 5/10, 2012 at 14:54 Comment(3)
Libraries at the end of the compiler command. See #9967459Ovotestis
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)Firebreak
@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)Raymundorayna
T
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.

Trichotomy answered 5/10, 2012 at 14:57 Comment(4)
Any idea how we can specify this using qmake?Noise
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!Incontinent
"Recent versions of GCC require..." But WHY? It worked before!Indamine
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 otherHolguin

© 2022 - 2024 — McMap. All rights reserved.