Ошибка загрузки модуля 'xxx' из файла './xxx.so'. в C++ . Но C . Так работает

Я пытаюсь скомпилировать простой файл c в.so и вызвать функцию из него из файла lua. Я взял пример отсюда

/* hellofunc.c (C) 2011 by Steve Litt
 * gcc -Wall -shared -fPIC -o power.so -I/usr/include/lua5.1 -llua5.1 hellofunc.c
 * Note the word "power" matches the string after the underscore in
 * function luaopen_power(). This is a must.
 * The -shared arg lets it compile to .so format.
 * The -fPIC is for certain situations and harmless in others.
 * On your computer, the -I and -l args will probably be different.
*/

#include <lua.h>                               /* Always include this */
#include <lauxlib.h>                           /* Always include this */
#include <lualib.h>                            /* Always include this */

static int isquare(lua_State *L){              /* Internal name of func */
    float rtrn = lua_tonumber(L, -1);      /* Get the single number arg */
    printf("Top of square(), nbr=%f\n",rtrn);
    lua_pushnumber(L,rtrn*rtrn);           /* Push the return */
    return 1;                              /* One return value */
}
static int icube(lua_State *L){                /* Internal name of func */
    float rtrn = lua_tonumber(L, -1);      /* Get the single number arg */
    printf("Top of cube(), number=%f\n",rtrn);
    lua_pushnumber(L,rtrn*rtrn*rtrn);      /* Push the return */
    return 1;                              /* One return value */
}


/* Register this file's functions with the
 * luaopen_libraryname() function, where libraryname
 * is the name of the compiled .so output. In other words
 * it's the filename (but not extension) after the -o
 * in the cc command.
 *
 * So for instance, if your cc command has -o power.so then
 * this function would be called luaopen_power().
 *
 * This function should contain lua_register() commands for
 * each function you want available from Lua.
 *
*/
int luaopen_power(lua_State *L){
    lua_register(
            L,               /* Lua state variable */
            "square",        /* func name as known in Lua */
            isquare          /* func name in this file */
            );  
    lua_register(L,"cube",icube);
    return 0;
}

Скачал заголовочные файлы для lua-5.1 из исходного кузницы и скопировал в /usr/include/lua5.1. И скомпилирован с помощью команды ниже gcc.

gcc -Wall -shared -fPIC -o power.so -I/usr/include/lua5.1 -llua-5.1  hellofunc.c

Теперь power.so создан, и мой скрипт lua такой, как показано ниже.

#!/usr/bin/lua
require("power")
print(square(1.414213598))
print(cube(5))

Теперь, когда я запускаю скрипт lua, он вызывает функции общей библиотеки, как и ожидалось, и дает результаты.

Но я намерен создать C++ dll с несколькими функциями, которые я могу вызвать из скриптов lua.

Поэтому я переименовал hellofunc.c в hellofunc.cpp

а также

добавленной

#include <lua.hpp>  

замена

  #include <lua.h>                               /* Always include this */
  #include <lauxlib.h>                           /* Always include this */
  #include <lualib.h>                            /* Always include this */

Теперь я скомпилировал файл cpp с помощью команды ниже

g++ -Wall -shared -fPIC -o power.so -I/usr/include/lua5.1 -llua-5.1 -ldl hellofunc.cpp -lstdc++

а также попробовал с

 g++ -Wall -shared -fPIC -o power.so -I/usr/include/lua5.1  hellofunc.cpp -lstdc++

power.so создается.

Но пока я запускаю скрипт lua, я вижу ошибку ссылки

/usr/bin/lua: error loading module 'power' from file './power.so':
        ./power.so: undefined symbol: luaopen_power
stack traceback:
        [C]: ?
        [C]: in function 'require'
        ./hellofunc.lua:3: in main chunk
        [C]: ?

Я сталкивался со многими сообщениями, упоминающими тот же самый пример, но я не видел никакого ответа для этой конкретной проблемы.

Я не понимаю, почему он работает с библиотекой c, а не с библиотекой C++.

Я также установил LD_LIBRARY_PATH в каталог, где создается power.so.

Может кто-нибудь объяснить, что может быть причиной этого?

0 ответов

Другие вопросы по тегам