【问题标题】:Compiling a Simple C lua5.0 Program, Undefined References [duplicate]编译一个简单的 C lua5.0 程序,未定义的引用 [重复]
【发布时间】:2023-03-08 15:40:02
【问题描述】:

我尝试编译这个简单的 Lua 教程程序:

#include <stdio.h>
#include <string.h>
#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>

    int main (void) {
      char buff[256];
      int error;
      lua_State *L = lua_open();   /* opens Lua */
      luaopen_base(L);             /* opens the basic library */
      luaopen_table(L);            /* opens the table library */
      luaopen_io(L);               /* opens the I/O library */
      luaopen_string(L);           /* opens the string lib. */
      luaopen_math(L);             /* opens the math lib. */

      while (fgets(buff, sizeof(buff), stdin) != NULL) {
        error = luaL_loadbuffer(L, buff, strlen(buff), "line") ||
                lua_pcall(L, 0, 0, 0);
        if (error) {
          fprintf(stderr, "%s", lua_tostring(L, -1));
          lua_pop(L, 1);  /* pop error message from the stack */
        }
      }

      lua_close(L);
      return 0;
    }

使用以下命令:

gcc -I/usr/include/lua50 -L/usr/lib/liblua50.a -llua50 luainterpret.c

所以标题是链接的,库二进制也应该链接吧?

但是我得到以下未定义的引用:

/tmp/ccA3kOUt.o: In function `main':
luainterpret.c:(.text+0x1b): undefined reference to `lua_open'
luainterpret.c:(.text+0x31): undefined reference to `luaopen_base'
luainterpret.c:(.text+0x40): undefined reference to `luaopen_table'
luainterpret.c:(.text+0x4f): undefined reference to `luaopen_io'
luainterpret.c:(.text+0x5e): undefined reference to `luaopen_string'
luainterpret.c:(.text+0x6d): undefined reference to `luaopen_math'
luainterpret.c:(.text+0xa1): undefined reference to `luaL_loadbuffer'
luainterpret.c:(.text+0xc3): undefined reference to `lua_pcall'
luainterpret.c:(.text+0xf6): undefined reference to `lua_tostring'
luainterpret.c:(.text+0x11f): undefined reference to `lua_settop'
luainterpret.c:(.text+0x152): undefined reference to `lua_close'
collect2: error: ld returned 1 exit status

我用 nm 检查了 /usr/lib/liblua50.a 文件,上面的函数确实在那里!为什么 gcc 然后无法找到所述功能? 谁能告诉我我做错了什么?

【问题讨论】:

    标签: c lua linker-errors dynamic-linking


    【解决方案1】:

    不要将库放在源文件之前(这会利用库中存在的函数),而是尝试将其放在之后,例如

    gcc -I/usr/include/lua50 -L/usr/lib/liblua50.a  luainterpret.c -llua50
    

    来自online gcc manual

    在命令的哪个位置编写此选项会有所不同;链接器按照指定的顺序搜索和处理库和目标文件。因此,foo.o -lz bar.o 在文件foo.o 之后但在bar.o 之前搜索库z。如果bar.o 引用了z 中的函数,则这些函数可能不会被加载。

    【讨论】:

    • 是的,就是这样!使用以下命令编译完成:gcc -I/usr/include/lua50 -L/usr/lib/ luainterpret.c -llua50 -llualib50 感谢您的帮助:)
    猜你喜欢
    • 2018-09-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多