繁体   English   中英

将类对象与 C++ 一起使用时出现未定义的引用错误

[英]Undefined reference error when using class objects with C++

我经历了多个堆栈溢出帖子,并尝试实现以下示例,该示例将 dlopen 与 C++ 对象类一起使用,我有以下代码。

1) 文件hello.cc

#include <stdio.h>
#include "hello.h"
A::A() {
    init1();
} 
void A::init1() {
    printf("\n init ");
} 

2) 文件hello.h

#include <iostream>
class A {
    public: 
         A();
         void init1();
         inline void fun () { cout << "\n Inside fun"; }
 };


 extern "C" A* createA() {
   return new A;
 }

}

3)文件main.cpp

#include<iostream>
#include<dlfcn.h>
#include "hello.h" 
using namespace std;
int main() {
    void *handle;
    handle = dlopen("./libhello.so", RTLD_LAZY | RTLD_GLOBAL);
    if (!handle) {
      cout << "The error is " << dlerror();
    }
    return 0 ;
 }

我正在使用以下步骤创建共享库

1) g++ -g -fPIC -c hello.cc
2) g++ -g -shared -o libhello.so hello.o
3) g++ -g -o myprog main.cpp -

main.cpp:(.text+0x18): undefined reference to `A::A()' . The function createA in hello.h is declared so the same can be used to dlsym
  1. 我无法在 dlsym 中使用 createA
  2. 即使我不使用 dlsym,我也会收到对 `A::A() 的未定义引用
  3. 我的查询是正确的是在 dlsym 中使用 C++ 类对象
  4. 从 dlopen 的人我无法推断 RTLD_LAZY RTLD_GLOBAL RTLD_NOW 标志的意义

只需在命令行中输入:

g++ -g -o myprog main.cpp -l hello -l dl  -L ./

当然 - 当你想在本地运行它时,需要用 -rpath 编译

.. -Wl,-rpath ./

更正 hello.h:

/* hello.h */

#include <cstdio>

class A {
    public: 
         A();
         void init1();
         inline void fun () { printf ("A::fun (this=%p)\n", this); }
 };

extern "C" A* createA();

你好.cc:

/* hello.cc */

#include <cstdio>

#include "hello.h"

A::A() {
    init1();
}

void A::init1() {
    printf("A::init1 this=%p\n", this);
}

extern "C" A* createA() {
    return new A;
} 

主.cc:

/* main.cc */

#include <cstdio>
#include <iostream>
#include <dlfcn.h>
#include "hello.h"

using namespace std;

typedef A *fun_createA();

int main() {
    void *handle;
    fun_createA *ptr_createA;
    A *myA;

    handle = dlopen("./libhello.so", RTLD_LAZY | RTLD_GLOBAL);
    if (!handle) {
      cout << "The error is " << dlerror();
    }
    ptr_createA = (fun_createA *)dlsym (handle, "createA");
    printf ("ptr_createA is %p\n", ptr_createA);

    myA = ptr_createA ();
    printf ("ptr_createA gave me %p\n", myA);

    myA->fun ();

    return 0;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM