c++ - 为什么在这种情况下编译动态库会出错呢?

标签 c++ linux .so

我在同一路径上写入了两个文件。 第一个文件名为“dso.h”。

//dso.cpp
#ifdef DSO_H
#define DSO_H

#include <string>
#include <map>

#include "spider.h"

using namespace std;

#define MODULE_OK  0
#define MODULE_ERR 1

#define MAGIC_MAJOR_NUMBER 1
#define MAGIC_MINOR_NUMBER 0

#define STANDARD_MODULE_STUFF MAGIC_MAJOR_NUMBER, MAGIC_MINOR_NUMBER,__FILE__


typedef struct Module{
        int version;
        int minor_version;
        const char * name;
        void (*init)(Module *);
        int (*handle)(void *);
} MODULE;


class ModuleManager
{
        public:
                ModuleManager();
                ~ModuleManager();

                int load(string path, string name);  
                MODULE * getModule(string name);

        private:
                map<string, MODULE*> m_modules; 
};


#endif

第二个文件名为“testmodule.cpp”

#include "dso.h"
#include <stdio.h>

extern int handle(void * data){
        printf("%s", (char *)data);
        return MODULE_OK;
}

extern int init(Module * module){
        module = &module;
        return MODULE_OK;
}


Module mod
{
        MODULE_MAJOR_VERSION,
        MODULE_SUB_VERSION,
        __FILE__,
        init,
        handle,
};

我尝试运行此命令:

g++ -shared -fPIC -o testmodule.so testmodule.cpp

运行该命令后,我收到一些错误,请参见下文

testmodule.cpp: In function ‘int handle(void*)’:
testmodule.cpp:6:10: error: ‘MODULE_OK’ was not declared in this scope
   return MODULE_OK;
          ^~~~~~~~~
testmodule.cpp: At global scope:
testmodule.cpp:9:17: warning: ‘init’ initialized and declared ‘extern’
 extern int init(Module * module){
                 ^~~~~~
testmodule.cpp:9:17: error: ‘Module’ was not declared in this scope
testmodule.cpp:9:17: note: suggested alternative: ‘double’
 extern int init(Module * module){
                 ^~~~~~
                 double
testmodule.cpp:9:26: error: ‘module’ was not declared in this scope
 extern int init(Module * module){
                          ^~~~~~
testmodule.cpp:9:26: note: suggested alternative: ‘double’
 extern int init(Module * module){
                          ^~~~~~
                          double
testmodule.cpp:15:1: error: ‘Module’ does not name a type; did you mean ‘double’?
 Module mod
 ^~~~~~
 double

我无法获取动态库,如何解决这个问题?

在 ubuntu18.04TLS linux 中运行上述命令。

最佳答案

看来您混淆了 dso.h 和 dso.cpp。 假设应该是 dso.h...

顶部的包含防护是错误的。

#ifdef DSO_H
#define DSO_H

...应该是

#ifndef DSO_H
#define DSO_H

否则 header 将不会被解析!

关于c++ - 为什么在这种情况下编译动态库会出错呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55165447/

相关文章:

c - 如何检查.so 中定义的宏?我会使用 nm 来检查功能,有没有办法对宏做同样的事情?

c++ - 如何在 C++ 中转发类的声明?

c++ - C++ 中 3 个类的多态性

linux - 使用 $ORIGIN 指定 ELF 二进制文件中的解释器不起作用

c - .so 文件如何查找符号?

c - Yocto-gcc 找不到共享库

c++ - 在 C 中,将函数指针赋值给适当类型的变量给出 "cannot convert ... in assignment"

c++ - ZeroMQ 是否允许多个服务器套接字?

linux - 我正在尝试按照以下模式获取组下的用户列表

linux - 将 linux 命令输出分配给 python 2.6.6 中的变量