
Include C headers in D code - atilaneves
https://atilanevesoncode.wordpress.com/2018/04/09/include-c-headers-in-d-code/
======
speps
Note that zig has a similar feature:
[https://ziglang.org/documentation/master/#Import-from-C-
Head...](https://ziglang.org/documentation/master/#Import-from-C-Header-File)

~~~
atilaneves
I didn't know about that, thanks for sharing.

------
atilaneves
Author here, AMA. This is a link to my blog post about a project that allows
one to directly #include C headers in D code, which can then be compiled and
linked. It's worked for non-trivial C libraries such as pthread, openssl and
libcurl.

~~~
flohofwoe
Awesome, this is exactly how I wish all 'better C' languages would allow C
interop instead of going through separate binding-generator tools. The C (not
C++) language itself is simple enough that at least a struct/function
declarations parser shouldn't add too much code to any compiler (even if not
using LLVM for this).

The best solution would be to also allow directly referencing .c
implementation files from D source, for separate compilation and linking with
the D program. Nim does allow something like this:
[https://github.com/floooh/sokol-
nim/blob/master/sokol/gfx.ni...](https://github.com/floooh/sokol-
nim/blob/master/sokol/gfx.nim#L10), but I guess since Nim compiles to C this
is much easier to achieve :)

~~~
atilaneves
The language that is commonly known as C is simple. Real C isn't because of
the preprocessor. There's no way to do it properly unless one uses an actual C
compiler.

Viva libclang!

------
Doxin
So why haven't you implemented this as a compile-time thing? It should be
fairly doable to parse and translate C headers to D code like that and then to
just mix it in. instead of needing a preprocessor you'd just get valid D code
using something like

    
    
        mixin(cHeader("headerfile.h"));

~~~
atilaneves
Because then I'd have to write a C parser that works at D compile-time. I'd
much rather use libclang and know that what I get was parsed correctly.
_Especially_ when I start doing C++.

~~~
Doxin
I suggest you look at the pegged library. It does compile-time parser
generation of parsers that work at compile time. I think the examples folder
contains a C grammar.

But then I suppose getting it working is better than getting it elegant.

