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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12748837/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 14:31:08  来源:igfitidea点击:

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

c++linuxshared-libraries

提问by fivunlm

I'm making a C++ Shared Library and when I compile a main exe that uses the library the compiler gives me:

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

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

Library code:

图书馆代码:

fooclass.h

fooclass.h

#ifndef __FOOCLASS_H__
#define __FOOCLASS_H__

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

#endif //__FOOCLASS_H__

fooclass.cpp

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

主: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

该机器是 Ubuntu Linux 12

Thanks!

谢谢!

采纳答案by fivunlm

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

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

g++ -I. -L. main.cpp -o main -lfoo

instead.

反而。