使用最小的C++/SWIG/Lua代码时发生共享dll链接错误。

这是一个涉及C ++、SWIG和Lua的非常特定的编译问题。

我有一个非常简单的基础代码:

_AClass.hpp_

class AClass {
public:
    AClass();
};

_AClass.cpp_

#include "AClass.hpp"

AClass::AClass() {}

_main.cpp_

#include "AClass.hpp"

int main() {
    AClass my_a;
}

此时,编译没有关系。我首先在libengine.dll中编译类,然后使用共享库构建可执行文件。

让我们引入一个SWIG模块,并将其添加到dll中:

_AClass.i_

%module M_AClass

%{
#include "AClass.hpp"
%}

%include "AClass.hpp"

从此时起,将所有内容链接到可执行文件中时,我会收到以下错误:

g++ -c main.cpp
g++ -c AClass.cpp
swig.exe -c++ -lua AClass.i
g++ -Iinclude -c AClass_wrap.cxx
g++ AClass.o AClass_wrap.o -shared -o libengine.dll -Wl,--out-implib,libengine.dll.a -L. -llua5.1
Creating library file: libengine.dll.a
g++ main.o libengine.dll.a -o main.exe
main.o:main.cpp:(.text+0x16): undefined reference to `AClass::AClass()'
collect2: ld returned 1 exit status

有人能给出线索吗?我尝试使用nm查看dll,但我无法弄清楚如何将另一个_.o_添加到共享库中,就可以“隐藏”方法(这不是特定于构造函数的)。


为了再现上下文,这里是将必要文件放入目录以构建测试的内容:

include/#包含“lauxlib.h”,“lua.h”和“luaconf.h”
liblua5.1.dll
AClass.hpp
AClass.cpp
AClass.i
main.cpp
Makefile

最后,这是Makefile内容:

ifneq($(findstring Linux,$(shell uname -o)),)
    EXEC:= main
    LIB:= libengine.so
    LIB_FLAGS:= -o $(LIB)
else
    EXEC:= main.exe
    LIB:= libengine.dll.a
    LIB_FLAGS:= -o libengine.dll -Wl,--out-implib,$(LIB)
    #如果没有差异,使用“.dll.a”与CMake中的(选项:-Wl,--out-implib,)或仅“.dll”

    ifdef SystemRoot
    #纯Windows,没有Cygwin
        RM:= del / Q
    endif
endif

LANG_LIB:= -L. -llua5.1
LANG_INC:= include
LANG_SWIG:= -lua

全部:清洁$(EXEC)

清洁:
    $(RM)main * .exe * _wrap.cxx * .o libengine.*

$(EXEC):main.o $(LIB)
    g ++ $ ^ -o $ @

main.o:main.cpp
    g ++ -c $ <

#没有依赖关系就没有问题
$(LIB):AClass.o AClass_wrap.o
    g ++ $ ^ -shared $(LANG_LIB)$(LIB_FLAGS)

AClass.o:AClass.cpp
    g ++ -fPIC -c $ <

AClass_wrap.o:AClass_wrap.cxx
    g ++ -fPIC -I $(LANG_INC)-c $ <

AClass_wrap.cxx:AClass.i
    swig -c ++ $(LANG_SWIG)$ <

这在Windows Seven下使用MingGW g ++ v4.5.2、SWIG 2.0.2和Lua5.1进行了测试。

EDIT:SWIG导出到tcl时也会出现问题。但是,在Linux下编译绝对没有问题。我比较了生成的AClass_wrap.cxx,它们是相似的。

原文链接 https://stackoverflow.com/questions/7655368

点赞
stackoverflow用户869951
stackoverflow用户869951

g++mingw 环境下可能需要使用 __declspec(dllimport/export)

2011-12-12 04:58:27