4 ms·
Include C headers in D code
- atilaneves 9y agoAuthor 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 9y agoAwesome, 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.nim#L10 https://github.com/floooh/sokol-nim/blob/master/sokol/gfx.ni..., but I guess since Nim compiles to C this is much easier to achieve :)
- atilaneves 9y agoThe 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!
- speps 9y agoNote that zig has a similar feature: https://ziglang.org/documentation/master/#Import-from-C-Header-File https://ziglang.org/documentation/master/#Import-from-C-Head...
- atilaneves 9y agoI didn't know about that, thanks for sharing.
- Doxin 9y agoSo 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 9y agoBecause 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 9y agoI 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.