Search code examples
luac++17gnu-makestatic-linking

Building and linking lua from source via makefile


I've tried to compile and link lua with my application. This is my makefile:

app.o: app.cpp
    g++ -c app.cpp

PATH_LUA=../lua-5.4.3/src
LUA= \
$(PATH_LUA)/lapi.c \
$(PATH_LUA)/lauxlib.c \
$(PATH_LUA)/lbaselib.c \
$(PATH_LUA)/lcode.c \
$(PATH_LUA)/lcorolib.c \
$(PATH_LUA)/lctype.c \
$(PATH_LUA)/ldblib.c \
$(PATH_LUA)/ldebug.c \
$(PATH_LUA)/ldo.c \
$(PATH_LUA)/ldump.c \
$(PATH_LUA)/lfunc.c \
$(PATH_LUA)/lgc.c \
$(PATH_LUA)/linit.c \
$(PATH_LUA)/liolib.c \
$(PATH_LUA)/llex.c \
$(PATH_LUA)/lmathlib.c \
$(PATH_LUA)/lmem.c \
$(PATH_LUA)/loadlib.c \
$(PATH_LUA)/lobject.c \
$(PATH_LUA)/lopcodes.c \
$(PATH_LUA)/loslib.c \
$(PATH_LUA)/lparser.c \
$(PATH_LUA)/lstate.c \
$(PATH_LUA)/lstring.c \
$(PATH_LUA)/lstrlib.c \
$(PATH_LUA)/ltable.c \
$(PATH_LUA)/ltablib.c \
$(PATH_LUA)/ltm.c \
$(PATH_LUA)/lundump.c \
$(PATH_LUA)/lutf8lib.c \
$(PATH_LUA)/lvm.c \
$(PATH_LUA)/lzio.c

libLua.so:
    g++ -shared $(LUA) -fPIC -o lua/libLua.so
 
all: libLua.so app.o
    g++ -o app app.o -I$(PATH_LUA) -lLua -Llua -ldl

The compilation works fine, but something is wrong with the linkage, because I get tons of undefined references to "lua_XYZ-function". The undefined reference to lua_tointegerx for example makes no sense, since its implementation is located in lapi.c which is in the file-list above.

(INB4: "This is a duplicate question!" … I've tried my best to check them all.)

What am I missing?


Solution

  • You have to compile lua as c++-code explicitly.

    You do this by including

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

    instead of #include <lua.hpp> which includes that extern "C" {...} statement.