Crystal库可以静态链接到C吗?

Lye*_*ish 19 crystal-lang

我已经阅读了教程中的"C绑定",但我是C的新手.

有人可以告诉我,如果一个Crystal程序可以构建为一个静态库来链接,如果可以的话,请你提供一个简单的例子吗?

Jon*_*Haß 26

是的,但不建议这样做.Crystal依赖于GC,因此不太可能生成共享(或静态)库.因此,也没有语法级别的构造来帮助创建这样的,也不需要简单的编译器调用.文档中的C绑定部分是关于使用C语言编写的库可用于Crystal程序.

无论如何,这是一个简单的例子:

logger.cr

fun init = crystal_init : Void
  # We need to initialize the GC
  GC.init

  # We need to invoke Crystal's "main" function, the one that initializes
  # all constants and runs the top-level code (none in this case, but without
  # constants like STDOUT and others the last line will crash).
  # We pass 0 and null to argc and argv.
  LibCrystalMain.__crystal_main(0, Pointer(Pointer(UInt8)).null)
end

fun log = crystal_log(text: UInt8*): Void
  puts String.new(text)
end
Run Code Online (Sandbox Code Playgroud)

logger.h

#ifndef _CRYSTAL_LOGGER_H
#define _CRYSTAL_LOGGER_H

void crystal_init(void);
void crystal_log(char* text);
#endif
Run Code Online (Sandbox Code Playgroud)

main.c中

#include "logger.h"

int main(void) {
  crystal_init();
  crystal_log("Hello world!");
}
Run Code Online (Sandbox Code Playgroud)

我们可以创建一个共享库

crystal build --single-module --link-flags="-shared" -o liblogger.so
Run Code Online (Sandbox Code Playgroud)

或者带有静态库

crystal build logger.cr --single-module --emit obj
rm logger # we're not interested in the executable
strip -N main logger.o # Drop duplicated main from the object file
ar rcs liblogger.a logger.o
Run Code Online (Sandbox Code Playgroud)

让我们确认我们的功能已包含在内

nm liblogger.so | grep crystal_
nm liblogger.a | grep crystal_
Run Code Online (Sandbox Code Playgroud)

好的,是时候编译我们的C程序了

# Folder where we can store either liblogger.so or liblogger.a but
# not both at the same time, so we can sure to use the right one
rm -rf lib
mkdir lib
cp liblogger.so lib
gcc main.c -o dynamic_main -Llib -llogger
LD_LIBRARY_PATH="lib" ./dynamic_main
Run Code Online (Sandbox Code Playgroud)

或静态版本

# Folder where we can store either liblogger.so or liblogger.a but
# not both at the same time, so we can sure to use the right one
rm -rf lib
mkdir lib
cp liblogger.a lib
gcc main.c -o static_main -Llib -levent -ldl -lpcl -lpcre -lgc -llogger
./static_main
Run Code Online (Sandbox Code Playgroud)

https://gist.github.com/3bd3aadd71db206e828f获得了很多灵感