Wednesday, June 14, 2017

Compiling and running SWIG for Lua in Ubuntu 16.04 using C++

This blog entry is quite similar to my previous entry. The difference is that this entry uses C++ source files instead of C.

We first start with the C++ header file:

Notice the use of extern for the declaration of the global variable, since we are dealing with C++ here and not C.

We then create the C++ implementation file:

Then we create the interface file for SWIG:

We then call SWIG to generate the wrapper file:

% swig -lua -c++ example.i

Notice the use of the -c++ argument.

Next, we compile the wrapper file:

% g++ -fPIC -I/usr/include/lua5.2 -c example_wrap.cxx -o example_wrap.o

Notice that the generated wrapper file has the file suffice .cxx

We then compile the C++ implementation file:

% g++ -fPIC -I. -c example.cpp -o example.o

Finally, we create the shared object to be used by our Lua script:

% g++ -shared -I/usr/include/lua5.2 example_wrap.o example.o -o example.so

We write a Lua script for testing:

When run:

% lua test.lua
3
120
2
Wed Jun 14 16:41:11 2017

Hope this helps the world. :)

No comments:

Post a Comment