【问题标题】:why compiling a dynamic library error in this situation?为什么在这种情况下编译动态库错误?
【发布时间】:2019-03-14 14:45:35
【问题描述】:

我在同一路径上写了两个文件。 第一个名为“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.cpp 的内容,这是一个源文件。该内容看起来应该在名为dso.h头文件 中。 testmodule.cpp 包含 头文件 dso.h,而不是源文件。
  • 顺便说一下,您的testmodule.cpp 代码中还有其他(逻辑)错误。就像定义和声明的顺序一样,您忘记了默认情况下参数是按值传递的(即,值被复制到本地参数变量中)。

标签: c++ linux .so


【解决方案1】:

您似乎混淆了 dso.h 和 dso.cpp。 假设应该是 dso.h...

在顶部,include-guard 是错误的。

#ifdef DSO_H
#define DSO_H

...应该是

#ifndef DSO_H
#define DSO_H

否则头部不会被解析!

【讨论】:

    猜你喜欢
    • 2018-04-10
    • 1970-01-01
    • 2016-02-29
    • 2015-01-05
    • 1970-01-01
    • 1970-01-01
    • 2014-04-12
    • 1970-01-01
    • 2011-07-05
    相关资源
    最近更新 更多