Crystal C binding, a simple greeting example.

Im trying to figure out how c bindings work in the crystal. For starters, Iโ€™m wondering how to include the simple hello world c function in the crystal. Is it always good to start with the basics? Here, the Id function should include:

#include <stdio.h> void hello(const char * name){ printf("Hello %s!\n", name); } 
+5
source share
1 answer

I also had to figure it out a bit. First you have to compile your C file into an object. In gcc, you run gcc -c hello.c -o hello.o .

Then in the crystal file you will need to link object C. Here is an example:

 #hello.cr @[Link(ldflags: "#{__DIR__}/hello.o")] lib Say fun hello(name : LibC::Char*) : Void end Say.hello("your name") 

Now you just need to compile your crystal application and it will work. crystal build hello.cr

+7
source

Source: https://habr.com/ru/post/1265406/


All Articles