Reputation:
I'm trying to bind a C++ (functional) lua extension as a static library to a host C++ program.
I made a minimalistic program to see if it's going to work properly. I currently have this code:
main.cpp :
#include "util.h"
int main()
{
lua_State* L;
startLua(L);//after the call to this is gets the segfault
luaL_dofile(L,"test.lua");
}
util.h :
#ifndef _UTIL_FILE_INCLUDED_
#define _UTIL_FILE_INCLUDED_
extern "C" {
#include <lua.h>
#include <lualib.h>
#include <lauxlib.h>
}
//functions
int startLua(lua_State* start);
#endif
util.cpp :
#include "util.h"
int startLua(lua_State* start)
{
//program never gets here
start = lua_open();
luaL_openlibs(start);
return 0;
}
Makefile :
CC=g++
CFLAGS=-c -Wall -fpermissive
LFLAGS=-llua
all: util.a main.o
$(CC) $(LFLAGS) main.o util.a -o main
util.a: util.o util.h
ar -cvq util.a util.o
util.o: util.cpp util.h
$(CC) $(CFLAGS) util.cpp
main.o: main.cpp util.h
$(CC) $(CFLAGS) main.cpp
clean:
rm *.o *.a
I also tried undefining L from the header and defining it purely inside of main(), with same result.
the only warning I get during compile is that "L is defined but not used" or "L is used uninitialized".
at runtime it starts by giving me out a segfault right away.
I don't exactly work with libraries that often, so it may be a fault there, in that case this should be a simple question.
In case it matters, I use gcc 4.7.2, lua 5.1.5 and Arch Linux (updated).
EDIT: According to GDB, the problem is here: Program received signal SIGSEGV, Segmentation fault. 0x00007ffff7bb6390 in lua_gettop () from /usr/lib/liblua.so.5.1
I never had problems with lua, is it possible that compiling it into a static library is a mistake?
Upvotes: 0
Views: 637
Reputation: 473232
lua_State* L;
startLua(L);//after the call to this is gets the segfault
This is a basic C problem here. You cannot change the value of parameters in C when they are passed by value.
startLua
sets the value of its parameter. But that doesn't affect L
at all. This isn't C++ (and even if it were, you didn't pass it by reference). If you want to affect L
, then you must pass a pointer to L
itself. As in &L
, and startLua
has to take a lua_State**
. And to set the value, it must dereference the pointer (*start = lua_open()
).
Or even better, just do this:
lua_State *L = startLua();
And have startLua
return the Lua state.
Upvotes: 2