C++共享库未定义引用`FooClass :: SayHello()'

fiv*_*nlm 20 c++ linux shared-libraries

我正在创建一个C++共享库,当我编译一个使用该库的主exe时,编译器给了我:

main.cpp:(.text+0x21): undefined reference to `FooClass::SayHello()'
collect2: ld returned 1 exit status
Run Code Online (Sandbox Code Playgroud)

图书馆代码:

fooclass.h

#ifndef __FOOCLASS_H__
#define __FOOCLASS_H__

class FooClass 
{
    public:
        char* SayHello();
};

#endif //__FOOCLASS_H__
Run Code Online (Sandbox Code Playgroud)

fooclass.cpp

#include "fooclass.h"

char* FooClass::SayHello() 
{
    return "Hello Im a Linux Shared Library";
}
Run Code Online (Sandbox Code Playgroud)

编译:

g++ -shared -fPIC fooclass.cpp -o libfoo.so
Run Code Online (Sandbox Code Playgroud)

主要: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;
}
Run Code Online (Sandbox Code Playgroud)

编译:

g++ -I. -L. -lfoo main.cpp -o main
Run Code Online (Sandbox Code Playgroud)

该机器是Ubuntu Linux 12

谢谢!

小智 41

g++ -I. -L. -lfoo main.cpp -o main
Run Code Online (Sandbox Code Playgroud)

是问题.最新版本的GCC要求您按照彼此依赖的顺序放置目标文件和库 - 作为一个相应的经验法则,您必须将库标志作为链接器的最后一个开关; 即写

g++ -I. -L. main.cpp -o main -lfoo
Run Code Online (Sandbox Code Playgroud)

代替.

  • 知道如何使用qmake指定这个吗? (3认同)
  • “GCC 的最新版本需要......”但是*为什么*?以前有用过! (2认同)