编译一个简单的 C lua5.0 程序,未定义的引用

我尝试编译这个简单的 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();   /* 打开 Lua */
      luaopen_base(L);             /* 打开基础库 */
      luaopen_table(L);            /* 打开表库 */
      luaopen_io(L);               /* 打开输入输出库 */
      luaopen_string(L);           /* 打开字符串库 */
      luaopen_math(L);             /* 打开数学库 */

      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);  /* 从堆栈中弹出错误消息 */
        }
      }

      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 找不到这些函数呢? 有人能告诉我我错在哪里吗?

点赞
用户2173917
用户2173917

不要把库放在源文件之前(这样可以使用库中的函数),尝试放在后面,例如:

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

来自在线 gcc 手册

在命令中写入此选项的位置很重要; 链接器按照指定的顺序搜索和处理库和对象文件。 因此,foo.o -lz bar.o 在文件 foo.o 之后但在 bar.o 之前搜索库 z。 如果 bar.o 引用 z 中的函数,则这些函数可能不会加载。

2019-03-29 11:33:16