Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Crystal C binding, simple hello world example.

I’m trying to figure out how c bindings in crystal work. For starters I’m wondering how I would include a simple hello world c function into crystal. Always good to start with the basics right? Here’s the function I’d like to include:

#include <stdio.h>

void hello(const char * name){
  printf("Hello %s!\n", name);
}
like image 592
Jake Avatar asked Mar 13 '17 21:03

Jake


1 Answers

That took me a bit to figure out as well. First you'll have to compile your C file into an object. In gcc you would run gcc -c hello.c -o hello.o.

Then in the crystal file you'll need to link to the C object. Here's an example:

#hello.cr
@[Link(ldflags: "#{__DIR__}/hello.o")]

lib Say 
  fun hello(name : LibC::Char*) : Void
end

Say.hello("your name")

Now you simply have to compile your crystal app and it will work. crystal build hello.cr

like image 139
isaacsloan Avatar answered Oct 19 '22 04:10

isaacsloan