093_hello_c.zig 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. //
  2. // When Andrew Kelley announced the idea of a new programming language
  3. // - namely Zig - in his blog on February 8, 2016, he also immediately
  4. // stated his ambitious goal: to replace the C language!
  5. //
  6. // In order to be able to achieve this goal at all, Zig should be
  7. // as compatible as possible with its "predecessor".
  8. // Only if it is possible to exchange individual modules in existing
  9. // C programs without having to use complicated wrappers,
  10. // the undertaking has a chance of success.
  11. //
  12. // So it is not surprising that calling C functions and vice versa
  13. // is extremely "smooth".
  14. //
  15. // To call C functions in Zig, you only need to specify the library
  16. // that contains said function. For this purpose there is a built-in
  17. // function corresponding to the well-known @import():
  18. //
  19. // @cImport()
  20. //
  21. // All required libraries can now be included in the usual Zig notation:
  22. //
  23. // const c = @cImport({
  24. // @cInclude("stdio.h");
  25. // @cInclude("...");
  26. // });
  27. //
  28. // Now a function can be called via the (in this example) constant 'c':
  29. //
  30. // c.puts("Hello world!");
  31. //
  32. // By the way, most C functions have return values in the form of an
  33. // integer value. Errors can then be evaluated (return < 0) or other
  34. // information can be obtained. For example, 'puts' returns the number
  35. // of characters output.
  36. //
  37. // So that all this does not remain a dry theroy now, let's just start
  38. // and call a C function out of Zig.
  39. // our well-known "import" for Zig
  40. const std = @import("std");
  41. // and here the new the import for C
  42. const c = @cImport({
  43. @cInclude("unistd.h");
  44. });
  45. pub fn main() void {
  46. // In order to output text that can be evaluated by the
  47. // Zig Builder, we need to write it to the Error output.
  48. // In Zig, we do this with "std.debug.print" and in C we can
  49. // specify a file descriptor i.e. 2 for error console.
  50. //
  51. // In this exercise we use 'write' to output 17 chars,
  52. // but something is still missing...
  53. const c_res = write(2, "Hello C from Zig!", 17);
  54. // let's see what the result from C is:
  55. std.debug.print(" - C result is {d} chars written.\n", .{c_res});
  56. }
  57. //
  58. // Something must be considered when compiling with C functions.
  59. // Namely that the Zig compiler knows that it should include
  60. // corresponding libraries. For this purpose we call the compiler
  61. // with the parameter "lc" for such a program,
  62. // e.g. "zig run -lc hello_c.zig".
  63. //