How do I compile code that uses Lua 5.1's C API?

2.1k views Asked by At

I have code that #includes the files lua.h, lapi.h, lualib.h, and lauxlib.h from Lua's source. Now I have to actually compile this code.

My first thought is to include all of the .c files in the Lua's source code or just figure out which of those .c files I actually need, but is there a better or even right way to compile code that uses Lua 5.1's C API?

I should add that I am a complete beginning to compilation, and I know next to nothing. I do know what GCC is and how to run it from the command line, but that's about it.


To be more specific, I know that my compilation command using GCC will look something like this:

gcc code.c

Now, do I need to add every file in the Lua source as an argument like this?

gcc code.c lapi.c lauxlib.c lbaselib.c lcode.c …

or is there a better way to do this?

1

There are 1 answers

6
Basile Starynkevitch On

A code that uses Lua API is just some C program which happens to use the Lua library. On my Linux/Debian system, that Lua library for developers is provided by the liblua5.3-dev Debian package. That package also has files for pkg-config

So you code your C program as usual. Probably, you'll use some build automation tool. On my Debian system, that could be make, ninja and many others. It is your choice and your responsibility to choose the right build automation tool.

Then you configure your build automation tool to pass relevant preprocessor flags to your C compiler, and to pass relevant linking flags at link time.

On my Linux system, I would choose to build with make, of course use the GCC compiler, and I would edit my Makefile (see this example) to contain things like:

CC= gcc
CFLAGS= -g $(shell pkg-config --cflags lua5.3) -Wall -Wextra
LDFLAGS+= $(shell pkg-config --libes lua5.3)

I do know what GCC is and how to run it from the command line,

You need to be sure to know how to practically use gcc to compile a program made of several translation units and using some external library. You also need to understand why build automation tools are so useful. Depending on your background, you might need to spend several weeks in reading more about that.

My recommendation: find some small free software program (e.g. on github) and study how it should be built (so learn enough to understand its build process). You'll learn a lot. Look into things like luakit