C ++共享库未定义引用`FooClass :: SayHello()' [英] C++ shared library undefined reference to `FooClass::SayHello()'

查看:228
本文介绍了C ++共享库未定义引用`FooClass :: SayHello()'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

图书馆代码:

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";
}

编译:

g++ -shared -fPIC fooclass.cpp -o libfoo.so

Main:
main.cpp

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;
}

编译:

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

机器是Ubuntu Linux 12

The machine is an Ubuntu Linux 12

谢谢!

推荐答案

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

是问题。最近的GCC版本要求您按照它们相互依赖的顺序放置对象文件和库 - 作为一个相应的经验法则,您必须将库标志作为链接器的最后一个开关;一世。 e。写

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

这篇关于C ++共享库未定义引用`FooClass :: SayHello()'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆