Reputation: 293
I am trying to learn how to embed lua in a C program, but I am not great at reading technical documents, and I haven't found any current tutorials. This is my program:
#include <iostream>
#include <lua.h>
#include <lualib.h>
#include <lauxlib.h>
void report_errors(lua_State*, int);
int main(int argc, char** argv) {
for (int n = 1; n < argc; ++n) {
const char* file = argv[n];
lua_State *L = luaL_newstate();
luaL_openlibs(L);
std::cerr << "-- Loading File: " << file << std::endl;
int s = luaL_loadfile(L, file);
if (s == 0) {
s = lua_pcall(L, 0, LUA_MULTRET, 0);
}
report_errors(L, s);
lua_close(L);
std::cerr << std::endl;
}
return 0;
}
void report_errors(lua_State *L, int status) {
if (status) {
std::cerr << "-- " << lua_tostring(L, -1) << std::endl;
lua_pop(L, 1);
}
}
The compiler gives undefined reference errors for luaL_newstate, luaL_openlibs, luaL_loadfilex, lua_pcallk, and lua_close. I am using Code::Blocks one a Windows computer and I have added the lua include directory to all of the search paths and liblua53.a to the link libraries. The IDE autocompleted the header names and the parser displays most of the lua functions, but with a brief search I found that the parser could not find either lua_newstate or luaL_newstate. Why does it find some of the functions and not others?
Upvotes: 4
Views: 4251
Reputation: 71
undefined reference to `luaL_newstate'
Need extern "C" wrapping and also as recommended above put "-llua" at the end.
extern "C" {
#include <lua5.3/lualib.h>
#include <lua5.3/lauxlib.h>
#include <lua5.3/lua.h>
}
gcc -o l -ldl l.cpp -llua5.3
Upvotes: 0
Reputation: 293
The arguments for g++ had -llua before the input file. I put -llua at the end, and everything works fine now.
Upvotes: 1
Reputation: 31419
In c++ you should include lua.hpp
not lua.h
. lua.h
does not define the extern "C"
block to stop the name mangling of the c++ compiler.
Upvotes: 6