Search code examples
crystal-langstatic-binding

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);
}

Solution

  • 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