lua 开发环境搭建

参考资料

lua 官网: https://www.lua.org/

luarocks 官网: https://luarocks.org/


Lua 最全的快速入门教程

lua从入门到进厂

Lua 包管理 – Luarocks 使用指南

Lua 5.4 中文参考手册

linux 下编译Lua源码,同时生成 动态库.so 静态库.a 文件

【最详细易懂】C++和Lua交互总结

C++与Lua联合编程实战

高性能混合编程:用脚本语言配合C++使用之Lua

用 lua 脚本配合 C++ 开发

(9)CMake入门笔记--同时生成动态库与静态库

Linux 基本环境搭建

lua 基本环境

下载 lua

wget https://www.lua.org/ftp/lua-5.4.2.tar.gz

编译 lua

直接 make 即可, 我把编译后的 lualuac 放在了 ~/program/lua/lua542, 然后将这个目录放入 ~/.bashrc 即可

测试 lua

laolang@laolang-mint:lua$ cat hello.lua 
print("Hello World")
laolang@laolang-mint:lua$ lua hello.lua 
Hello World
laolang@laolang-mint:lua$ 

luarocks 基本环境

下载 luarocks

wget https://luarocks.org/releases/luarocks-3.11.1.tar.gz

安装 luarocks

解压后执行 ./configure 提示

laolang@laolang-mint:luarocks-3.11.1$ ./configure 

Configuring LuaRocks version 3.11.1...

Lua version detected: 5.4
Lua interpreter found: /home/laolang/program/lua/lua542/lua
lua.h for Lua 5.4 not found (tried /home/laolang/program/lua/include/lua/5.4/lua.h /home/laolang/program/lua/include/lua5.4/lua.h /home/laolang/program/lua/include/lua-5.4/lua.h /home/laolang/program/lua/include/lua54/lua.h /home/laolang/program/lua/include/lua.h)

If the development files for Lua (headers and libraries)
are installed in your system, you may need to use the
--with-lua or --with-lua-include flags to specify their location.

If those files are not yet installed, you need to install
them using the appropriate method for your operating system.

Run ./configure --help for details on flags.

configure failed.

laolang@laolang-mint:luarocks-3.11.1$ which lua
/home/laolang/program/lua/lua542/lua
laolang@laolang-mint:luarocks-3.11.1$ 

根据提示, 将 lua 头文件放入 ~/program/lua/include/lua/5.4 , 然后再次执行 ./configure
lua 头文件

laolang@laolang-mint:5.4$ pwd
/home/laolang/program/lua/include/lua/5.4
laolang@laolang-mint:5.4$ l
总计 216K
-rw-r--r-- 1 laolang laolang 1.3K 2024-06-01 17:10:06 lapi.h
-rw-r--r-- 1 laolang laolang 8.7K 2024-06-01 17:10:06 lauxlib.h
-rw-r--r-- 1 laolang laolang 3.8K 2024-06-01 17:10:06 lcode.h
-rw-r--r-- 1 laolang laolang 2.1K 2024-06-01 17:10:06 lctype.h
-rw-r--r-- 1 laolang laolang 1.9K 2024-06-01 17:10:06 ldebug.h
-rw-r--r-- 1 laolang laolang 2.8K 2024-06-01 17:10:06 ldo.h
-rw-r--r-- 1 laolang laolang 1.8K 2024-06-01 17:10:06 lfunc.h
-rw-r--r-- 1 laolang laolang 5.9K 2024-06-01 17:10:06 lgc.h
-rw-r--r-- 1 laolang laolang 1.7K 2024-06-01 17:10:06 ljumptab.h
-rw-r--r-- 1 laolang laolang 2.4K 2024-06-01 17:10:06 llex.h
-rw-r--r-- 1 laolang laolang 8.8K 2024-06-01 17:10:06 llimits.h
-rw-r--r-- 1 laolang laolang 3.3K 2024-06-01 17:10:06 lmem.h
-rw-r--r-- 1 laolang laolang  22K 2024-06-01 17:10:06 lobject.h
-rw-r--r-- 1 laolang laolang  13K 2024-06-01 17:10:06 lopcodes.h
-rw-r--r-- 1 laolang laolang 1.2K 2024-06-01 17:10:06 lopnames.h
-rw-r--r-- 1 laolang laolang 5.8K 2024-06-01 17:10:06 lparser.h
-rw-r--r-- 1 laolang laolang  828 2024-06-01 17:10:06 lprefix.h
-rw-r--r-- 1 laolang laolang  14K 2024-06-01 17:10:06 lstate.h
-rw-r--r-- 1 laolang laolang 1.6K 2024-06-01 17:10:06 lstring.h
-rw-r--r-- 1 laolang laolang 2.0K 2024-06-01 17:10:06 ltable.h
-rw-r--r-- 1 laolang laolang 2.9K 2024-06-01 17:10:06 ltm.h
-rw-r--r-- 1 laolang laolang  21K 2024-06-01 17:10:06 luaconf.h
-rw-r--r-- 1 laolang laolang  16K 2024-06-01 17:10:06 lua.h
-rw-r--r-- 1 laolang laolang  191 2024-06-01 17:10:06 lua.hpp
-rw-r--r-- 1 laolang laolang 1.2K 2024-06-01 17:10:06 lualib.h
-rw-r--r-- 1 laolang laolang  863 2024-06-01 17:10:06 lundump.h
-rw-r--r-- 1 laolang laolang 4.3K 2024-06-01 17:10:06 lvm.h
-rw-r--r-- 1 laolang laolang 1.5K 2024-06-01 17:10:06 lzio.h
laolang@laolang-mint:5.4$ 

./configure

laolang@laolang-mint:luarocks-3.11.1$ ./configure 

Configuring LuaRocks version 3.11.1...

Lua version detected: 5.4
Lua interpreter found: /home/laolang/program/lua/lua542/lua
lua.h found: /home/laolang/program/lua/include/lua/5.4/lua.h
unzip found in PATH: /usr/bin

Done configuring.

LuaRocks will be installed at......: /usr/local
LuaRocks will install rocks at.....: /usr/local
LuaRocks configuration directory...: /usr/local/etc/luarocks
Using Lua from.....................: /home/laolang/program/lua

* Type make and make install:
  to install to /usr/local as usual.
* Type make bootstrap:
  to install LuaRocks into /usr/local as a rock.

laolang@laolang-mint:luarocks-3.11.1$ 

然后执行 make && sudo make install 即可

luarocks 安装后的配置

此时直接执行 luarocks 会提示

laolang@laolang-mint:lua-hello$ luarocks
Variables:
   Variables from the "variables" table of the configuration file can be
   overridden with VAR=VALUE assignments.

Configuration:
   Lua:
      Version    : 5.4
      LUA        : /home/laolang/program/lua/lua542/lua (ok)
      LUA_INCDIR : (lua.h not found) 看这里看这里看这里看这里看这里
                   ****************************************
                   Use the command

                      luarocks config variables.LUA_INCDIR <dir>

                   to fix the location
                   ****************************************
      LUA_LIBDIR : (Lua library itself not found)
                   ****************************************
                   Use the command

                      luarocks config variables.LUA_LIBDIR <dir>

                   to fix the location
                   ****************************************

   Configuration files:
      System  : /usr/local/etc/luarocks/config-5.4.lua (ok)
      User    : /home/laolang/.luarocks/config-5.4.lua (ok)

   Rocks trees in use:
      /home/laolang/.luarocks ("user")
      /usr/local ("system")

laolang@laolang-mint:lua-hello$ 

解决这个问题很简单, 只需要再复制一次 lua 头文件到 lua 可执行程序所在目录即可

laolang@laolang-mint:lua542$ tree
.
├── include
│   └── lua
│       └── 5.4
│           ├── lapi.h
│           ├── lauxlib.h
│           ├── lcode.h
│           ├── lctype.h
│           ├── ldebug.h
│           ├── ldo.h
│           ├── lfunc.h
│           ├── lgc.h
│           ├── ljumptab.h
│           ├── llex.h
│           ├── llimits.h
│           ├── lmem.h
│           ├── lobject.h
│           ├── lopcodes.h
│           ├── lopnames.h
│           ├── lparser.h
│           ├── lprefix.h
│           ├── lstate.h
│           ├── lstring.h
│           ├── ltable.h
│           ├── ltm.h
│           ├── luaconf.h
│           ├── lua.h
│           ├── lua.hpp
│           ├── lualib.h
│           ├── lundump.h
│           ├── lvm.h
│           └── lzio.h
├── lua
└── luac

3 directories, 30 files
laolang@laolang-mint:lua542$ 

luarocks 安装库测试

然后安装两个库

luarocks install --tree=rocks luasocket
luarocks install --tree=rocks lualogging

安装过程如下

laolang@laolang-mint:lua-hello$ luarocks install --tree=rocks luasocket
Installing https://luarocks.org/luasocket-3.1.0-1.src.rock

luasocket 3.1.0-1 depends on lua >= 5.1 (5.4-1 provided by VM: success)
gcc -O2 -fPIC -I/home/laolang/program/lua/lua542/include/lua/5.4 -c src/luasocket.c -o src/luasocket.o -DLUASOCKET_DEBUG
gcc -O2 -fPIC -I/home/laolang/program/lua/lua542/include/lua/5.4 -c src/timeout.c -o src/timeout.o -DLUASOCKET_DEBUG
gcc -O2 -fPIC -I/home/laolang/program/lua/lua542/include/lua/5.4 -c src/buffer.c -o src/buffer.o -DLUASOCKET_DEBUG
gcc -O2 -fPIC -I/home/laolang/program/lua/lua542/include/lua/5.4 -c src/io.c -o src/io.o -DLUASOCKET_DEBUG
gcc -O2 -fPIC -I/home/laolang/program/lua/lua542/include/lua/5.4 -c src/auxiliar.c -o src/auxiliar.o -DLUASOCKET_DEBUG
gcc -O2 -fPIC -I/home/laolang/program/lua/lua542/include/lua/5.4 -c src/options.c -o src/options.o -DLUASOCKET_DEBUG
gcc -O2 -fPIC -I/home/laolang/program/lua/lua542/include/lua/5.4 -c src/inet.c -o src/inet.o -DLUASOCKET_DEBUG
gcc -O2 -fPIC -I/home/laolang/program/lua/lua542/include/lua/5.4 -c src/except.c -o src/except.o -DLUASOCKET_DEBUG
gcc -O2 -fPIC -I/home/laolang/program/lua/lua542/include/lua/5.4 -c src/select.c -o src/select.o -DLUASOCKET_DEBUG
gcc -O2 -fPIC -I/home/laolang/program/lua/lua542/include/lua/5.4 -c src/tcp.c -o src/tcp.o -DLUASOCKET_DEBUG
gcc -O2 -fPIC -I/home/laolang/program/lua/lua542/include/lua/5.4 -c src/udp.c -o src/udp.o -DLUASOCKET_DEBUG
gcc -O2 -fPIC -I/home/laolang/program/lua/lua542/include/lua/5.4 -c src/compat.c -o src/compat.o -DLUASOCKET_DEBUG
gcc -O2 -fPIC -I/home/laolang/program/lua/lua542/include/lua/5.4 -c src/usocket.c -o src/usocket.o -DLUASOCKET_DEBUG
gcc  -shared -o /tmp/luarocks_build-LuaSocket-3.1.0-1-9566323/socket/core.so src/luasocket.o src/timeout.o src/buffer.o src/io.o src/auxiliar.o src/options.o src/inet.o src/except.o src/select.o src/tcp.o src/udp.o src/compat.o src/usocket.o
gcc -O2 -fPIC -I/home/laolang/program/lua/lua542/include/lua/5.4 -c src/buffer.c -o src/buffer.o -DLUASOCKET_DEBUG
gcc -O2 -fPIC -I/home/laolang/program/lua/lua542/include/lua/5.4 -c src/compat.c -o src/compat.o -DLUASOCKET_DEBUG
gcc -O2 -fPIC -I/home/laolang/program/lua/lua542/include/lua/5.4 -c src/auxiliar.c -o src/auxiliar.o -DLUASOCKET_DEBUG
gcc -O2 -fPIC -I/home/laolang/program/lua/lua542/include/lua/5.4 -c src/options.c -o src/options.o -DLUASOCKET_DEBUG
gcc -O2 -fPIC -I/home/laolang/program/lua/lua542/include/lua/5.4 -c src/timeout.c -o src/timeout.o -DLUASOCKET_DEBUG
gcc -O2 -fPIC -I/home/laolang/program/lua/lua542/include/lua/5.4 -c src/io.c -o src/io.o -DLUASOCKET_DEBUG
gcc -O2 -fPIC -I/home/laolang/program/lua/lua542/include/lua/5.4 -c src/usocket.c -o src/usocket.o -DLUASOCKET_DEBUG
gcc -O2 -fPIC -I/home/laolang/program/lua/lua542/include/lua/5.4 -c src/serial.c -o src/serial.o -DLUASOCKET_DEBUG
gcc  -shared -o /tmp/luarocks_build-LuaSocket-3.1.0-1-9566323/socket/serial.so src/buffer.o src/compat.o src/auxiliar.o src/options.o src/timeout.o src/io.o src/usocket.o src/serial.o
gcc -O2 -fPIC -I/home/laolang/program/lua/lua542/include/lua/5.4 -c src/mime.c -o src/mime.o -DLUASOCKET_DEBUG
gcc -O2 -fPIC -I/home/laolang/program/lua/lua542/include/lua/5.4 -c src/compat.c -o src/compat.o -DLUASOCKET_DEBUG
gcc  -shared -o /tmp/luarocks_build-LuaSocket-3.1.0-1-9566323/mime/core.so src/mime.o src/compat.o
gcc -O2 -fPIC -I/home/laolang/program/lua/lua542/include/lua/5.4 -c src/buffer.c -o src/buffer.o -DLUASOCKET_DEBUG
gcc -O2 -fPIC -I/home/laolang/program/lua/lua542/include/lua/5.4 -c src/compat.c -o src/compat.o -DLUASOCKET_DEBUG
gcc -O2 -fPIC -I/home/laolang/program/lua/lua542/include/lua/5.4 -c src/auxiliar.c -o src/auxiliar.o -DLUASOCKET_DEBUG
gcc -O2 -fPIC -I/home/laolang/program/lua/lua542/include/lua/5.4 -c src/options.c -o src/options.o -DLUASOCKET_DEBUG
gcc -O2 -fPIC -I/home/laolang/program/lua/lua542/include/lua/5.4 -c src/timeout.c -o src/timeout.o -DLUASOCKET_DEBUG
gcc -O2 -fPIC -I/home/laolang/program/lua/lua542/include/lua/5.4 -c src/io.c -o src/io.o -DLUASOCKET_DEBUG
gcc -O2 -fPIC -I/home/laolang/program/lua/lua542/include/lua/5.4 -c src/usocket.c -o src/usocket.o -DLUASOCKET_DEBUG
gcc -O2 -fPIC -I/home/laolang/program/lua/lua542/include/lua/5.4 -c src/unix.c -o src/unix.o -DLUASOCKET_DEBUG
gcc -O2 -fPIC -I/home/laolang/program/lua/lua542/include/lua/5.4 -c src/unixdgram.c -o src/unixdgram.o -DLUASOCKET_DEBUG
gcc -O2 -fPIC -I/home/laolang/program/lua/lua542/include/lua/5.4 -c src/unixstream.c -o src/unixstream.o -DLUASOCKET_DEBUG
gcc  -shared -o /tmp/luarocks_build-LuaSocket-3.1.0-1-9566323/socket/unix.so src/buffer.o src/compat.o src/auxiliar.o src/options.o src/timeout.o src/io.o src/usocket.o src/unix.o src/unixdgram.o src/unixstream.o
No existing manifest. Attempting to rebuild...
luasocket 3.1.0-1 is now installed in /home/laolang/code/lua/lua-hello/rocks (license: MIT)

laolang@laolang-mint:lua-hello$ luarocks install --tree=rocks lualogging
Installing https://luarocks.org/lualogging-1.8.2-1.src.rock

lualogging 1.8.2-1 depends on luasocket (3.1.0-1 installed: success)
lualogging 1.8.2-1 is now installed in /home/laolang/code/lua/lua-hello/rocks (license: MIT/X11)

laolang@laolang-mint:lua-hello$ 

测试文件内容如下

package.path = package.path .. ";./rocks/share/lua/5.4/?.lua"
require("logging")

if #arg > 0 then
    if arg[1] ~= nil and arg[1] == "on" then
        local dbg = require("emmy_core")
        dbg.tcpListen("localhost", 9966)
        dbg.waitIDE()
    end
end

local Logging = require "logging"

local appender = function(self, level, message)
    print(level, message)
    return true
end

local logger = Logging.new(appender)
logger:setLevel(logger.INFO)
logger:info("Hello Lua")

执行结果

laolang@laolang-mint:lua-hello$ lua main.lua 
INFO	Hello Lua
laolang@laolang-mint:lua-hello$ 

C++ 与 lua 混合编程

创建 lua 动态库

目录结构

laolang@laolang-mint:lua_lib$ tree
.
├── CMakeLists.txt
├── CMakePresets.json
├── include
│   ├── lapi.h
│   ├── lauxlib.h
│   ├── lcode.h
│   ├── lctype.h
│   ├── ldebug.h
│   ├── ldo.h
│   ├── lfunc.h
│   ├── lgc.h
│   ├── ljumptab.h
│   ├── llex.h
│   ├── llimits.h
│   ├── lmem.h
│   ├── lobject.h
│   ├── lopcodes.h
│   ├── lopnames.h
│   ├── lparser.h
│   ├── lprefix.h
│   ├── lstate.h
│   ├── lstring.h
│   ├── ltable.h
│   ├── ltm.h
│   ├── luaconf.h
│   ├── lua.h
│   ├── lua.hpp
│   ├── lualib.h
│   ├── lundump.h
│   ├── lvm.h
│   └── lzio.h
└── src
    ├── lapi.c
    ├── lauxlib.c
    ├── lbaselib.c
    ├── lcode.c
    ├── lcorolib.c
    ├── lctype.c
    ├── ldblib.c
    ├── ldebug.c
    ├── ldo.c
    ├── ldump.c
    ├── lfunc.c
    ├── lgc.c
    ├── linit.c
    ├── liolib.c
    ├── llex.c
    ├── lmathlib.c
    ├── lmem.c
    ├── loadlib.c
    ├── lobject.c
    ├── lopcodes.c
    ├── loslib.c
    ├── lparser.c
    ├── lstate.c
    ├── lstring.c
    ├── lstrlib.c
    ├── ltable.c
    ├── ltablib.c
    ├── ltm.c
    ├── lundump.c
    ├── lutf8lib.c
    ├── lvm.c
    └── lzio.c

2 directories, 62 files
laolang@laolang-mint:lua_lib$ 

CMakeLists.txt

注意:
src 目录中没有 lua.cluac.c
其实有也不要紧, 在 CMakeLists.txt 中手动指定了源文件列表

cmake_minimum_required(VERSION 3.26)

set(CMAKE_C_STANDARD 17)
set(CMAKE_C_STANDARD_REQUIRED True)
set(CMAKE_C_EXTENSIONS OFF)

project(lua LANGUAGES C)

include_directories(${PROJECT_SOURCE_DIR}/include)

set(src_list
src/lapi.c
src/lauxlib.c
src/lbaselib.c
src/lcode.c
src/lcorolib.c
src/lctype.c
src/ldblib.c
src/ldebug.c
src/ldo.c
src/ldump.c
src/lfunc.c
src/lgc.c
src/linit.c
src/liolib.c
src/llex.c
src/lmathlib.c
src/lmem.c
src/loadlib.c
src/lobject.c
src/lopcodes.c
src/loslib.c
src/lparser.c
src/lstate.c
src/lstring.c
src/lstrlib.c
src/ltable.c
src/ltablib.c
src/ltm.c
src/lundump.c
src/lutf8lib.c
src/lvm.c
src/lzio.c
)

# 生成动态库
add_library(${PROJECT_NAME} SHARED ${src_list})
# 设置动态库版本
SET_TARGET_PROPERTIES(${PROJECT_NAME} PROPERTIES VERSION 5.4.2 SOVERSION 5)
# 生成静态库
add_library(${PROJECT_NAME}_static STATIC ${src_list})

# 使动态库和静态库同时存在
set_target_properties(${PROJECT_NAME}_static PROPERTIES OUTPUT_NAME ${PROJECT_NAME})
set_target_properties(${PROJECT_NAME} PROPERTIES CLEAN_DIRECT_OUTPUT 1)

CMakePresets.json

注意:ninja路径修改为自己的实际路径

{
    "version": 6,
    "cmakeMinimumRequired": {
        "major": 3,
        "minor": 26,
        "patch": 0
    },
    "configurePresets": [
        {
            "name": "windows-base",
            "displayName": "preset base",
            "description": "通用设置",
            "cacheVariables": {
                "CMAKE_MAKE_PROGRAM": "D:/program/qt/Tools/Ninja/ninja.exe",
                "CMAKE_GENERATOR": "Ninja",
                "CMAKE_C_COMPILER": "D:/program/qt/Tools/mingw1120_64/bin/gcc.exe",
                "CMAKE_C_FLAGS": "-Wall -Wextra"
            }
        },
        {
            "name": "windows-release",
            "displayName": "windows release",
            "description": "使用 ninja 与 g++ 构建 release 版本",
            "inherits": "windows-base",
            "binaryDir": "${sourceDir}/build/ninja-release",
            "cacheVariables": {
                "CMAKE_BUILD_TYPE": "Release"
            }
        },
        {
            "name": "windows-debug",
            "displayName": "windows debug",
            "description": "使用 ninja 与 g++ 构建 debug 版本",
            "inherits": "windows-base",
            "binaryDir": "${sourceDir}/build/ninja-debug",
            "cacheVariables": {
                "CMAKE_BUILD_TYPE": "Debug",
                "CMAKE_DEBUG_POSTFIX": "d"
            }
        },
        {
            "name": "linux-base",
            "displayName": "preset base",
            "description": "通用设置",
            "cacheVariables": {
                "CMAKE_GENERATOR": "Ninja",
                "CMAKE_MAKE_PROGRAM": "/home/laolang/.local/bin/ninja",
                "CMAKE_C_COMPILER": "/usr/bin/gcc",
                "CMAKE_C_FLAGS": "-Wall -Wextra"
            }
        },
        {
            "name": "linux-release",
            "displayName": "linux release",
            "description": "使用 ninja 与 g++ 构建 release 版本",
            "inherits": "linux-base",
            "binaryDir": "${sourceDir}/build/ninja-release",
            "cacheVariables": {
                "CMAKE_BUILD_TYPE": "Release"
            }
        },
        {
            "name": "linux-debug",
            "displayName": "linux debug",
            "description": "使用 ninja 与 g++ 构建 debug 版本",
            "inherits": "linux-base",
            "binaryDir": "${sourceDir}/build/ninja-debug",
            "cacheVariables": {
                "CMAKE_BUILD_TYPE": "Debug",
                "CMAKE_DEBUG_POSTFIX": "d"
            }
        }
    ],
    "buildPresets": [
        {
            "name": "windows-release",
            "configurePreset": "windows-release"
        },
        {
            "name": "windows-debug",
            "configurePreset": "windows-debug"
        },
        {
            "name": "linux-release",
            "configurePreset": "linux-release"
        },
        {
            "name": "linux-debug",
            "configurePreset": "linux-debug"
        }
    ]
}

生成动态库

cmake --preset=linux-release && cmake --build --preset=linux-release

构建过程如下

laolang@laolang-mint:lua_lib$ cmake --preset=linux-release && cmake --build --preset=linux-release
Preset CMake variables:

  CMAKE_BUILD_TYPE="Release"
  CMAKE_C_COMPILER="/usr/bin/gcc"
  CMAKE_C_FLAGS="-Wall -Wextra"
  CMAKE_GENERATOR="Ninja"
  CMAKE_MAKE_PROGRAM="/home/laolang/.local/bin/ninja"

-- The C compiler identification is GNU 11.4.0
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Check for working C compiler: /usr/bin/gcc - skipped
-- Detecting C compile features
-- Detecting C compile features - done
-- Configuring done (0.2s)
-- Generating done (0.0s)
-- Build files have been written to: /home/laolang/program/lua/lua_lib/build/ninja-release
[64/67] Linking C shared library liblua.so.5.4.2
/usr/bin/ld: CMakeFiles/lua.dir/src/loslib.c.o: in function `os_tmpname':
loslib.c:(.text+0x405): 警告: the use of `tmpnam' is dangerous, better use `mkstemp'
[67/67] Linking C static library liblua.a
laolang@laolang-mint:lua_lib$ l build/ninja-release/
总计 1.1M
-rw-rw-r-- 1 laolang laolang  53K 2024-06-01 17:28:58 build.ninja
-rw-rw-r-- 1 laolang laolang  13K 2024-06-01 17:28:58 CMakeCache.txt
drwxrwxr-x 7 laolang laolang 4.0K 2024-06-01 17:28:58 CMakeFiles/
-rw-rw-r-- 1 laolang laolang 1.7K 2024-06-01 17:28:58 cmake_install.cmake
-rw-rw-r-- 1 laolang laolang 595K 2024-06-01 17:29:00 liblua.a
lrwxrwxrwx 1 laolang laolang   11 2024-06-01 17:28:59 liblua.so -> liblua.so.5*
lrwxrwxrwx 1 laolang laolang   15 2024-06-01 17:28:59 liblua.so.5 -> liblua.so.5.4.2*
-rwxrwxr-x 1 laolang laolang 353K 2024-06-01 17:28:59 liblua.so.5.4.2*
laolang@laolang-mint:lua_lib$ 

使用动态库

目录结构

注意:
需要复制上一步编译好的 lua 动态库

laolang@laolang-mint:test$ tree
.
├── CMakeLists.txt
├── CMakePresets.json
├── copylib.sh
├── lib
│   ├── liblua.so
│   ├── liblua.so.5
│   └── liblua.so.5.4.2
├── lua
│   └── main.lua
├── main.cpp
├── Makefile
└── third
    └── lua
        ├── lapi.h
        ├── lauxlib.h
        ├── lcode.h
        ├── lctype.h
        ├── ldebug.h
        ├── ldo.h
        ├── lfunc.h
        ├── lgc.h
        ├── ljumptab.h
        ├── llex.h
        ├── llimits.h
        ├── lmem.h
        ├── lobject.h
        ├── lopcodes.h
        ├── lopnames.h
        ├── lparser.h
        ├── lprefix.h
        ├── lstate.h
        ├── lstring.h
        ├── ltable.h
        ├── ltm.h
        ├── luaconf.h
        ├── lua.h
        ├── lua.hpp
        ├── lualib.h
        ├── lundump.h
        ├── lvm.h
        └── lzio.h

4 directories, 37 files
laolang@laolang-mint:test$ 

main.cpp

#include <iostream>

extern "C" {
#include <lua/lauxlib.h>
#include <lua/lua.h>
#include <lua/lualib.h>
}

int main() {
    // 创建 lua 状态
    lua_State *L = luaL_newstate();

    // 启用基本的 lua 库
    luaopen_base(L);

    // 加载 lua 文件
    luaL_loadfile(L, "main.lua");

    // 运行 lua 文件
    int ret = lua_pcall(L, 0, 0, 0);
    std::cout << "ret:" << ret << std::endl;

    return 0;
}

CMakeLists.txt

注意 windows 与 linux 的区别

# 指定 cmake 最小版本, 意指 cmake 版本小于指定版本则构建过程终止
cmake_minimum_required(VERSION 3.26)

#[[
    语言环境配置
]]

# 语言版本
set(CMAKE_CXX_STANDARD 17)

# 如果指定的语言版本不受支持, 则构建过程终止
set(CMAKE_CXX_STANDARD_REQUIRED True)

# 只弃用 ISO C++ 标准的编译器标志, 而不使用特定编译器的扩展
set(CMAKE_CXX_EXTENSIONS OFF)

if(UNIX)
    # 将 install_rpath 的设置应用在 build_rpath 上 避免在开发期间出现动态库找不到的问题
    set(CMAKE_BUILD_WITH_INSTALL_RPATH True)
endif()

#[[
    项目配置
]]

# 项目名称和语言
project( graver LANGUAGES CXX VERSION 1.0.0)

# 发布目录
set(dist_dir ${CMAKE_BINARY_DIR}/dist)

# 二进制文件目录
set(bin_dir ${dist_dir}/bin)
file(MAKE_DIRECTORY ${bin_dir})

if(UNIX)
    # 库文件目录
    set(lib_dir ${dist_dir}/lib)
    file(MAKE_DIRECTORY ${lib_dir})
endif()

#[[
    编译相关配置
]]

# 生成 compile_commands.json
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)

# 复制 lua 脚本
configure_file(${PROJECT_SOURCE_DIR}/lua/main.lua ${bin_dir}/)

# 包含全局头文件
include_directories(${PROJECT_SOURCE_DIR}/third)

# 添加库链接路径
# 添加库链接路径
if(UNIX)
    link_directories(${lib_dir})
elseif(WIN32)
    link_directories(${bin_dir})
endif()

# 源文件列表
aux_source_directory(. SRCS_MAIN)

# 生成可执行程序
add_executable(${PROJECT_NAME} ${SRCS_MAIN})

# 链接 lua 库
target_link_libraries(${PROJECT_NAME} lua)

# 可执行程序路径
set_target_properties(${PROJECT_NAME} PROPERTIES RUNTIME_OUTPUT_DIRECTORY ${bin_dir})

# 设置可执行程序 rpath
if(UNIX)
    set_target_properties(${PROJECT_NAME} PROPERTIES INSTALL_RPATH "\${ORIGIN}/../lib")
endif()

CMakePresets.json

注意:
g++ ninja 等设置为自己的实际路径

{
    "version": 6,
    "cmakeMinimumRequired": {
        "major": 3,
        "minor": 26,
        "patch": 0
    },
    "configurePresets": [
        {
            "name": "windows-base",
            "displayName": "preset base",
            "description": "通用设置",
            "cacheVariables": {
                "CMAKE_MAKE_PROGRAM": "D:/program/qt/Tools/Ninja/ninja.exe",
                "CMAKE_GENERATOR": "Ninja",
                "CMAKE_CXX_COMPILER": "D:/program/qt/Tools/mingw1120_64/bin/g++.exe",
                "CMAKE_CXX_FLAGS": "-Wall -Wextra"
            }
        },
        {
            "name": "windows-release",
            "displayName": "windows release",
            "description": "使用 ninja 与 g++ 构建 release 版本",
            "inherits": "windows-base",
            "binaryDir": "${sourceDir}/build/ninja-release",
            "cacheVariables": {
                "CMAKE_BUILD_TYPE": "Release"
            }
        },
        {
            "name": "windows-debug",
            "displayName": "windows debug",
            "description": "使用 ninja 与 g++ 构建 debug 版本",
            "inherits": "windows-base",
            "binaryDir": "${sourceDir}/build/ninja-debug",
            "cacheVariables": {
                "CMAKE_BUILD_TYPE": "Debug",
                "CMAKE_DEBUG_POSTFIX": "d"
            }
        },
        {
            "name": "linux-base",
            "displayName": "preset base",
            "description": "通用设置",
            "cacheVariables": {
                "CMAKE_MAKE_PROGRAM": "/home/laolang/.local/bin/ninja",
                "CMAKE_GENERATOR": "Ninja",
                "CMAKE_CXX_COMPILER": "/usr/bin/g++",
                "CMAKE_CXX_FLAGS": "-Wall -Wextra"
            }
        },
        {
            "name": "linux-release",
            "displayName": "linux release",
            "description": "使用 ninja 与 g++ 构建 release 版本",
            "inherits": "linux-base",
            "binaryDir": "${sourceDir}/build/ninja-release",
            "cacheVariables": {
                "CMAKE_BUILD_TYPE": "Release"
            }
        },
        {
            "name": "linux-debug",
            "displayName": "linux debug",
            "description": "使用 ninja 与 g++ 构建 debug 版本",
            "inherits": "linux-base",
            "binaryDir": "${sourceDir}/build/ninja-debug",
            "cacheVariables": {
                "CMAKE_BUILD_TYPE": "Debug",
                "CMAKE_DEBUG_POSTFIX": "d"
            }
        }
    ],
    "buildPresets": [
        {
            "name": "windows-release",
            "configurePreset": "windows-release"
        },
        {
            "name": "windows-debug",
            "configurePreset": "windows-debug"
        },
        {
            "name": "linux-release",
            "configurePreset": "linux-release"
        },
        {
            "name": "linux-debug",
            "configurePreset": "linux-debug"
        }
    ]
}

copylib.sh

注意 windows 和 linux 的区别

#!/bin/bash

if [ "$OSTYPE" == "linux-gnu" ]; then
    mkdir -p build/ninja-release/dist/lib
    cp lib/liblua.so*.* build/ninja-release/dist/lib/
elif [ "$MSYSTEM" == "MINGW64" ]; then
	mkdir -p build/ninja-release/dist/bin
	cp lib/*.dll build/ninja-release/dist/bin/
    cp lib/*.dll.a build/ninja-release/dist/bin/
fi

Makefile

ALL:run

.PHONY: copylib configure build run rebuild rerun clean format
copylib:
	bash copylib.sh

configure: copylib
	cmake --preset=linux-release
build: configure
	cmake --build --preset=linux-release
run: build
	cd build/ninja-release/dist/bin && ./graver
rebuild: clean build
rerun: rebuild run
clean:
	rm -rf build
format:
	# 格式化 c++ 代码
	find src -type f \( -name "*.c" -o -name "*.cc" -o -name "*.cpp" -o -name "*.h" -o -name "*.hpp" \) -exec clang-format -style=file:.clang-format -i {} \;
	find include -type f \( -name "*.c" -o -name "*.cc" -o -name "*.cpp" -o -name "*.h" -o -name "*.hpp" \) -exec clang-format -style=file:.clang-format -i {} \;
	# 格式化 CMakeLists.txt
	cmake-format -c .cmake-format.py -i CMakeLists.txt
	cmake-format -c .cmake-format.py -i src/CMakeLists.txt
	cmake-format -c .cmake-format.py -i src/app/CMakeLists.txt
	cmake-format -c .cmake-format.py -i src/lua/CMakeLists.txt

测试

直接 make 即可

laolang@laolang-mint:test$ make
bash copylib.sh
cmake --preset=linux-release
Preset CMake variables:

  CMAKE_BUILD_TYPE="Release"
  CMAKE_CXX_COMPILER="/usr/bin/g++"
  CMAKE_CXX_FLAGS="-Wall -Wextra"
  CMAKE_GENERATOR="Ninja"
  CMAKE_MAKE_PROGRAM="/home/laolang/.local/bin/ninja"

-- The CXX compiler identification is GNU 11.4.0
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Check for working CXX compiler: /usr/bin/g++ - skipped
-- Detecting CXX compile features
-- Detecting CXX compile features - done
-- Configuring done (0.1s)
-- Generating done (0.0s)
-- Build files have been written to: /home/laolang/code/lua/lua542/test/build/ninja-release
cmake --build --preset=linux-release
[2/2] Linking CXX executable dist/bin/graver
cd build/ninja-release/dist/bin && ./graver
Hello lua
ret:0
laolang@laolang-mint:test$ 

windows 基本环境搭建

lua 基本环境

下载

注意:
需要下载二进制包和源码包

二进制包

https://luabinaries.sourceforge.net/download.html

image

源码包

https://www.lua.org/ftp/lua-5.4.2.tar.gz

安装

将下载的两个二进制包的内容全部解压到同一个目录, 有提示覆盖, 直接是, 覆盖即可

image

然后将 lua54.exelua54c.exe 复制一份并改名, 再将目录添加到 path

image

测试 lua

E:\code\lua\lua-hello>type main.lua
print("Hello Lua")

E:\code\lua\lua-hello>lua main.lua
Hello Lua

E:\code\lua\lua-hello>

luarocks

下载

http://luarocks.github.io/luarocks/releases/

image

http://luarocks.github.io/luarocks/releases/luarocks-3.11.1-windows-64.zip

然后将 luarocks 压缩包的内容全部解压到 lua.exe 所在目录

image

安装后的配置

此时直接运行 luarocks 提示如下

Variables:
   Variables from the "variables" table of the configuration file can be
   overridden with VAR=VALUE assignments.

Configuration:
   Lua:
      Version    : 5.4
      LUA        : D:\program\lua\lua542\bin\lua54.exe (ok)
      LUA_INCDIR : D:\program\lua\lua542\bin/include (lua.h not found) 看这里 看这里 看这里
                   ****************************************
                   Use the command

                      luarocks config variables.LUA_INCDIR <dir>

                   to fix the location
                   ****************************************
      LUA_LIBDIR : D:/program/lua/lua542/bin (ok)

   Configuration files:
      System  : C:\Program Files\luarocks\config-5.4.lua (not found)
      User    : C:\Users\laolang\AppData\Roaming\luarocks\config-5.4.lua (ok)

   Rocks trees in use:
      C:\Users\laolang\AppData\Roaming\luarocks ("user")


E:\code\lua\lua-hello>

根据提示复制头文件即可

image

E:\code\lua\lua-hello>luarocks

Variables:
   Variables from the "variables" table of the configuration file can be
   overridden with VAR=VALUE assignments.

Configuration:
   Lua:
      Version    : 5.4
      LUA        : D:\program\lua\lua542\bin\lua54.exe (ok) 看这三行 
      LUA_INCDIR : D:\program\lua\lua542\bin/include (ok) 看这三行
      LUA_LIBDIR : D:/program/lua/lua542/bin (ok) 看这三行

   Configuration files:
      System  : C:\Program Files\luarocks\config-5.4.lua (not found)
      User    : C:\Users\laolang\AppData\Roaming\luarocks\config-5.4.lua (ok)

   Rocks trees in use:
      C:\Users\laolang\AppData\Roaming\luarocks ("user")


E:\code\lua\lua-hello>

安装依赖的前置准备

此时执行 luarocks install --tree=rocks luasocket 依然报错

E:\code\lua\lua-hello>luarocks install --tree=rocks luasocket
Installing https://luarocks.org/luasocket-3.1.0-1.src.rock

luasocket 3.1.0-1 depends on lua >= 5.1 (5.4-1 provided by VM: success)
x86_64-w64-mingw32-gcc -O2 -c -o src/mime.o -ID:\program\lua\lua542\bin/include src/mime.c -DLUASOCKET_DEBUG -DWINVER=0x0501 -Ic:\windows\system32\include
x86_64-w64-mingw32-gcc -O2 -c -o src/compat.o -ID:\program\lua\lua542\bin/include src/compat.c -DLUASOCKET_DEBUG -DWINVER=0x0501 -Ic:\windows\system32\include
x86_64-w64-mingw32-gcc  -shared -o C:\Users\laolang\AppData\Local\Temp\luarocks_build-LuaSocket-3.1.0-1-299710\mime\core.dll src/mime.o src/compat.o -Lc:\windows\system32 D:\program\lua\lua542\bin\lua54.dll -lm
D:/program/qt/Tools/mingw1120_64/bin/../lib/gcc/x86_64-w64-mingw32/11.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: D:/program/qt/Tools/mingw1120_64/bin/../lib/gcc/x86_64-w64-mingw32/11.2.0/../../../../x86_64-w64-mingw32/lib/../lib/dllcrt2.o:crtdll.c:(.text+0x16a): undefined reference to `_execute_onexit_table'
D:/program/qt/Tools/mingw1120_64/bin/../lib/gcc/x86_64-w64-mingw32/11.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: D:/program/qt/Tools/mingw1120_64/bin/../lib/gcc/x86_64-w64-mingw32/11.2.0/../../../../x86_64-w64-mingw32/lib/../lib/dllcrt2.o:crtdll.c:(.text+0x8): undefined reference to `_initialize_onexit_table'
D:/program/qt/Tools/mingw1120_64/bin/../lib/gcc/x86_64-w64-mingw32/11.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: D:/program/qt/Tools/mingw1120_64/bin/../lib/gcc/x86_64-w64-mingw32/11.2.0/../../../../x86_64-w64-mingw32/lib/../lib/dllcrt2.o:crtdll.c:(.text+0x35b): undefined reference to `_register_onexit_function'
D:/program/qt/Tools/mingw1120_64/bin/../lib/gcc/x86_64-w64-mingw32/11.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: D:/program/qt/Tools/mingw1120_64/bin/../lib/gcc/x86_64-w64-mingw32/11.2.0/../../../../x86_64-w64-mingw32/lib/../lib/libmingw32.a(lib64_libmingw32_a-pseudo-reloc.o):pseudo-reloc.c:(.text+0x28): undefined reference to `__acrt_iob_func'
D:/program/qt/Tools/mingw1120_64/bin/../lib/gcc/x86_64-w64-mingw32/11.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: D:/program/qt/Tools/mingw1120_64/bin/../lib/gcc/x86_64-w64-mingw32/11.2.0/../../../../x86_64-w64-mingw32/lib/../lib/libmingw32.a(lib64_libmingw32_a-pseudo-reloc.o):pseudo-reloc.c:(.text+0x51): undefined reference to `__acrt_iob_func'
collect2.exe: error: ld returned 1 exit status

Error: Build error: Failed compiling module mime\core.dll

E:\code\lua\lua-hello>

这是因为运行环境不正确, 我们应该使用 visual studio 的命令行

image

此时依然会报错

**********************************************************************
** Visual Studio 2022 Developer Command Prompt v17.9.1
** Copyright (c) 2022 Microsoft Corporation
**********************************************************************
[vcvarsall.bat] Environment initialized for: 'x64'

E:\code\lua\lua-hello>luarocks install --tree=rocks luasocket
Installing https://luarocks.org/luasocket-3.1.0-1.src.rock

luasocket 3.1.0-1 depends on lua >= 5.1 (5.4-1 provided by VM: success)

Error: Build error: Failed finding the Lua library. You can use `luarocks config variables.LUA_LIBDIR <path>` to set the correct location.

E:\code\lua\lua-hello>

我们需要下载 visual studio 对应的静态库, visual studio 版本与 vc 版本的对应关系

image

我的是 vs2022 , 所以下载的是 vc17.lib , 下载地址: https://sourceforge.net/projects/luabinaries/files/5.4.2/Windows%20Libraries/Static/

image

然后我们将静态库复制到 lua.exe 所在目录

image

再次执行如下命令

luarocks install --tree=rocks luasocket
luarocks install --tree=rocks lualogging

过程如下

E:\code\lua\lua-hello>luarocks install --tree=rocks luasocket
Installing https://luarocks.org/luasocket-3.1.0-1.src.rock

luasocket 3.1.0-1 depends on lua >= 5.1 (5.4-1 provided by VM: success)
cl /nologo /MD /O2 -c -Fosrc/luasocket.obj -ID:\program\lua\lua542\bin/include src/luasocket.c -DLUASOCKET_DEBUG -DNDEBUG -Ic:\windows\system32\include
luasocket.c
cl /nologo /MD /O2 -c -Fosrc/timeout.obj -ID:\program\lua\lua542\bin/include src/timeout.c -DLUASOCKET_DEBUG -DNDEBUG -Ic:\windows\system32\include
timeout.c
cl /nologo /MD /O2 -c -Fosrc/buffer.obj -ID:\program\lua\lua542\bin/include src/buffer.c -DLUASOCKET_DEBUG -DNDEBUG -Ic:\windows\system32\include
buffer.c
cl /nologo /MD /O2 -c -Fosrc/io.obj -ID:\program\lua\lua542\bin/include src/io.c -DLUASOCKET_DEBUG -DNDEBUG -Ic:\windows\system32\include
io.c
cl /nologo /MD /O2 -c -Fosrc/auxiliar.obj -ID:\program\lua\lua542\bin/include src/auxiliar.c -DLUASOCKET_DEBUG -DNDEBUG -Ic:\windows\system32\include
auxiliar.c
cl /nologo /MD /O2 -c -Fosrc/options.obj -ID:\program\lua\lua542\bin/include src/options.c -DLUASOCKET_DEBUG -DNDEBUG -Ic:\windows\system32\include
options.c
cl /nologo /MD /O2 -c -Fosrc/inet.obj -ID:\program\lua\lua542\bin/include src/inet.c -DLUASOCKET_DEBUG -DNDEBUG -Ic:\windows\system32\include
inet.c
cl /nologo /MD /O2 -c -Fosrc/except.obj -ID:\program\lua\lua542\bin/include src/except.c -DLUASOCKET_DEBUG -DNDEBUG -Ic:\windows\system32\include
except.c
cl /nologo /MD /O2 -c -Fosrc/select.obj -ID:\program\lua\lua542\bin/include src/select.c -DLUASOCKET_DEBUG -DNDEBUG -Ic:\windows\system32\include
select.c
cl /nologo /MD /O2 -c -Fosrc/tcp.obj -ID:\program\lua\lua542\bin/include src/tcp.c -DLUASOCKET_DEBUG -DNDEBUG -Ic:\windows\system32\include
tcp.c
cl /nologo /MD /O2 -c -Fosrc/udp.obj -ID:\program\lua\lua542\bin/include src/udp.c -DLUASOCKET_DEBUG -DNDEBUG -Ic:\windows\system32\include
udp.c
cl /nologo /MD /O2 -c -Fosrc/compat.obj -ID:\program\lua\lua542\bin/include src/compat.c -DLUASOCKET_DEBUG -DNDEBUG -Ic:\windows\system32\include
compat.c
cl /nologo /MD /O2 -c -Fosrc/wsocket.obj -ID:\program\lua\lua542\bin/include src/wsocket.c -DLUASOCKET_DEBUG -DNDEBUG -Ic:\windows\system32\include
wsocket.c
link -dll -def:core.def -out:C:\Users\laolang\AppData\Local\Temp\luarocks_build-LuaSocket-3.1.0-1-3920812\socket\core.dll D:\program\lua\lua542\bin\lua54.lib src/luasocket.obj src/timeout.obj src/buffer.obj src/io.obj src/auxiliar.obj src/options.obj src/inet.obj src/except.obj src/select.obj src/tcp.obj src/udp.obj src/compat.obj src/wsocket.obj ws2_32.lib
Microsoft (R) Incremental Linker Version 14.39.33520.0
Copyright (C) Microsoft Corporation.  All rights reserved.

  正在创建库 C:\Users\laolang\AppData\Local\Temp\luarocks_build-LuaSocket-3.1.0-1-3920812\socket\core.lib 和对象 C:\Users\laolang\AppData\Local\Temp\luarocks_build-LuaSocket-3.1.0-1-3920812\socket\core.exp
LINK : warning LNK4098: 默认库“LIBCMT”与其他库的使用冲突;请使用 /NODEFAULTLIB:library
cl /nologo /MD /O2 -c -Fosrc/mime.obj -ID:\program\lua\lua542\bin/include src/mime.c -DLUASOCKET_DEBUG -DNDEBUG -Ic:\windows\system32\include
mime.c
cl /nologo /MD /O2 -c -Fosrc/compat.obj -ID:\program\lua\lua542\bin/include src/compat.c -DLUASOCKET_DEBUG -DNDEBUG -Ic:\windows\system32\include
compat.c
link -dll -def:core.def -out:C:\Users\laolang\AppData\Local\Temp\luarocks_build-LuaSocket-3.1.0-1-3920812\mime\core.dll D:\program\lua\lua542\bin\lua54.lib src/mime.obj src/compat.obj -libpath:c:\windows\system32
Microsoft (R) Incremental Linker Version 14.39.33520.0
Copyright (C) Microsoft Corporation.  All rights reserved.

  正在创建库 C:\Users\laolang\AppData\Local\Temp\luarocks_build-LuaSocket-3.1.0-1-3920812\mime\core.lib 和对象 C:\Users\laolang\AppData\Local\Temp\luarocks_build-LuaSocket-3.1.0-1-3920812\mime\core.exp
LINK : warning LNK4098: 默认库“LIBCMT”与其他库的使用冲突;请使用 /NODEFAULTLIB:library
No existing manifest. Attempting to rebuild...
luasocket 3.1.0-1 is now installed in E:\code\lua\lua-hello\rocks (license: MIT)


E:\code\lua\lua-hello>luarocks install --tree=rocks lualogging
Installing https://luarocks.org/lualogging-1.8.2-1.src.rock

lualogging 1.8.2-1 depends on luasocket (3.1.0-1 installed: success)
lualogging 1.8.2-1 is now installed in E:\code\lua\lua-hello\rocks (license: MIT/X11)


E:\code\lua\lua-hello>

测试脚本

package.path = package.path .. ";./rocks/share/lua/5.4/?.lua"
require("logging")

-- if #arg > 0 then
--     if arg[1] ~= nil and arg[1] == "on" then
--         local dbg = require("emmy_core")
--         dbg.tcpListen("localhost", 9966)
--         dbg.waitIDE()
--     end
-- end

local Logging = require "logging"

local appender = function(self, level, message)
    print(level, message)
    return true
end

local logger = Logging.new(appender)
logger:setLevel(logger.INFO)
logger:info("Hello Lua")

测试结果

E:\code\lua\lua-hello>lua main.lua
INFO    Hello Lua

E:\code\lua\lua-hello>

C++ 与 lua 混合编程

注意:
需要在 git bash 中运行

将 linux 的工程直接复制到 windows

注意:
某些 exe 的路径修改为自己系统的实际值

image

编译动态库

laolang@DESKTOP-O12ME4M MINGW64 /e/code/lua/lua542/lua_lib
$ pwd
/e/code/lua/lua542/lua_lib

laolang@DESKTOP-O12ME4M MINGW64 /e/code/lua/lua542/lua_lib
$ ll
total 16
-rw-r--r-- 1 laolang 197121 1070  6月  1 18:37 CMakeLists.txt
-rw-r--r-- 1 laolang 197121 2986  6月  1 18:37 CMakePresets.json
drwxr-xr-x 1 laolang 197121    0  6月  1 18:37 include/
drwxr-xr-x 1 laolang 197121    0  6月  1 18:37 src/

laolang@DESKTOP-O12ME4M MINGW64 /e/code/lua/lua542/lua_lib
$ cmake --preset=windows-release
Preset CMake variables:

  CMAKE_BUILD_TYPE="Release"
  CMAKE_C_COMPILER="D:/program/qt/Tools/mingw1120_64/bin/gcc.exe"
  CMAKE_C_FLAGS="-Wall -Wextra"
  CMAKE_GENERATOR="Ninja"
  CMAKE_MAKE_PROGRAM="D:/program/qt/Tools/Ninja/ninja.exe"

-- The C compiler identification is GNU 11.2.0
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Check for working C compiler: D:/program/qt/Tools/mingw1120_64/bin/gcc.exe - skipped
-- Detecting C compile features
-- Detecting C compile features - done
-- Configuring done (0.6s)
-- Generating done (0.0s)
-- Build files have been written to: E:/code/lua/lua542/lua_lib/build/ninja-release

laolang@DESKTOP-O12ME4M MINGW64 /e/code/lua/lua542/lua_lib
$ cmake --build --preset=windows-release
[1/66] Building C object CMakeFiles/lua.dir/src/lcorolib.c.obj
...
[64/66] Linking C shared library liblua.dll
[65/66] Building C object CMakeFiles/lua_static.dir/src/lvm.c.obj
[66/66] Linking C static library liblua.a

laolang@DESKTOP-O12ME4M MINGW64 /e/code/lua/lua542/lua_lib
$ ls -l build/ninja-release/
total 1112
-rw-r--r-- 1 laolang 197121  52679  6月  1 18:39 build.ninja
-rw-r--r-- 1 laolang 197121   1607  6月  1 18:39 cmake_install.cmake
-rw-r--r-- 1 laolang 197121  14538  6月  1 18:39 CMakeCache.txt
drwxr-xr-x 1 laolang 197121      0  6月  1 18:39 CMakeFiles/
-rw-r--r-- 1 laolang 197121 433062  6月  1 18:39 liblua.a
-rwxr-xr-x 1 laolang 197121 413755  6月  1 18:39 liblua.dll*
-rw-r--r-- 1 laolang 197121 205782  6月  1 18:39 liblua.dll.a

laolang@DESKTOP-O12ME4M MINGW64 /e/code/lua/lua542/lua_lib
$

测试混编

需要修改 Makefile

ALL:run

.PHONY: copylib configure build run rebuild rerun clean format
copylib:
	bash copylib.sh

configure: copylib
	cmake --preset=windows-release # 注意这里
build: configure
	cmake --build --preset=windows-release # 以及这里
run: build
	cd build/ninja-release/dist/bin && ./graver
rebuild: clean build
rerun: rebuild run
clean:
	rm -rf build
format:
	# 格式化 c++ 代码
	find src -type f \( -name "*.c" -o -name "*.cc" -o -name "*.cpp" -o -name "*.h" -o -name "*.hpp" \) -exec clang-format -style=file:.clang-format -i {} \;
	find include -type f \( -name "*.c" -o -name "*.cc" -o -name "*.cpp" -o -name "*.h" -o -name "*.hpp" \) -exec clang-format -style=file:.clang-format -i {} \;
	# 格式化 CMakeLists.txt
	cmake-format -c .cmake-format.py -i CMakeLists.txt
	cmake-format -c .cmake-format.py -i src/CMakeLists.txt
	cmake-format -c .cmake-format.py -i src/app/CMakeLists.txt
	cmake-format -c .cmake-format.py -i src/lua/CMakeLists.txt

需要把上一步编译的 dll 复制到 lib 目录

测试过程

laolang@DESKTOP-O12ME4M MINGW64 /e/code/lua/lua542/test
$ pwd
/e/code/lua/lua542/test

laolang@DESKTOP-O12ME4M MINGW64 /e/code/lua/lua542/test
$ ll
total 18
-rw-r--r-- 1 laolang 197121 1750  6月  1 18:49 CMakeLists.txt
-rw-r--r-- 1 laolang 197121 2994  6月  1 18:36 CMakePresets.json
-rwxr-xr-x 1 laolang 197121  320  6月  1 18:46 copylib.sh*
drwxr-xr-x 1 laolang 197121    0  6月  1 18:45 lib/
drwxr-xr-x 1 laolang 197121    0  6月  1 18:37 lua/
-rw-r--r-- 1 laolang 197121  419  6月  1 18:36 main.cpp
-rw-r--r-- 1 laolang 197121  925  6月  1 18:42 Makefile
drwxr-xr-x 1 laolang 197121    0  6月  1 18:37 third/

laolang@DESKTOP-O12ME4M MINGW64 /e/code/lua/lua542/test
$ make
bash copylib.sh
cmake --preset=windows-release
Preset CMake variables:

  CMAKE_BUILD_TYPE="Release"
  CMAKE_CXX_COMPILER="D:/program/qt/Tools/mingw1120_64/bin/g++.exe"
  CMAKE_CXX_FLAGS="-Wall -Wextra"
  CMAKE_GENERATOR="Ninja"
  CMAKE_MAKE_PROGRAM="D:/program/qt/Tools/Ninja/ninja.exe"

-- The CXX compiler identification is GNU 11.2.0
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Check for working CXX compiler: D:/program/qt/Tools/mingw1120_64/bin/g++.exe - skipped
-- Detecting CXX compile features
-- Detecting CXX compile features - done
-- Configuring done (0.6s)
-- Generating done (0.0s)
-- Build files have been written to: E:/code/lua/lua542/test/build/ninja-release
cmake --build --preset=windows-release
[1/2] Building CXX object CMakeFiles/graver.dir/main.cpp.obj
[2/2] Linking CXX executable dist\bin\graver.exe
cd build/ninja-release/dist/bin && ./graver
Hello lua
ret:0

laolang@DESKTOP-O12ME4M MINGW64 /e/code/lua/lua542/test
$

待完成项

  1. Makefile 优化
  2. C++ 与 lua 混编时, 调用 luarocks 安装的依赖的问题
  3. lua 源码加入到 C++ 工程, 一次性完成编译 lua 库与 C++ lua 混编
posted @ 2024-06-01 16:59  潼关路边的一只野鬼  阅读(22)  评论(0编辑  收藏  举报