Can a Crystal library be statically linked to from C? -


i've read through "c bindings" in tutorial i'm novice @ c stuff.

could please let me know if crystal program can built static library link to, , if please provide simple example?

yes, not recommended so. crystal depends on gc makes less desirable produce shared (or static) libraries. there no syntax level constructs aid in creation of such nor simple compiler invocation so. c bindings section in documentation making libraries written in c available crystal programs.

here's simple example anyhow:

logger.cr

fun init = crystal_init : void   # need initialize gc   gc.init    # need invoke crystal's "main" function, 1 initializes   # constants , runs top-level code (none in case, without   # constants stdout , others last line crash).   # pass 0 , null argc , argv.   libcrystalmain.__crystal_main(0, pointer(pointer(uint8)).null) end  fun log = crystal_log(text: uint8*): void   puts string.new(text) end 

logger.h

#ifndef _crystal_logger_h #define _crystal_logger_h  void crystal_init(void); void crystal_log(char* text); #endif 

main.c

#include "logger.h"  int main(void) {   crystal_init();   crystal_log("hello world!"); } 

we can create shared library

crystal build --single-module --link-flags="-shared" -o liblogger.so 

or static library

crystal build logger.cr --single-module --emit obj rm logger # we're not interested in executable strip -n main logger.o # drop duplicated main object file ar rcs liblogger.a logger.o 

let's confirm our functions got included

nm liblogger.so | grep crystal_ nm liblogger.a | grep crystal_ 

alright, time compile our c program

# folder can store either liblogger.so or liblogger.a # not both @ same time, can sure use right 1 rm -rf lib mkdir lib cp liblogger.so lib gcc main.c -o dynamic_main -llib -llogger ld_library_path="lib" ./dynamic_main 

or static version

# folder can store either liblogger.so or liblogger.a # not both @ same time, can sure use right 1 rm -rf lib mkdir lib cp liblogger.a lib gcc main.c -o static_main -llib -levent -ldl -lpcl -lpcre -lgc -llogger ./static_main 

with inspiration https://gist.github.com/3bd3aadd71db206e828f


Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -