hello_world.carbon 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. // Part of the Carbon Language project, under the Apache License v2.0 with LLVM
  2. // Exceptions. See /LICENSE for license information.
  3. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. import Cpp library "<cstdio>";
  5. import Cpp library "<iostream>";
  6. import Cpp library "<string_view>";
  7. import Cpp library "<unistd.h>";
  8. // Demonstrate passing `char`s to a C++ function.
  9. fn HelloPutchar() {
  10. let message: array(char, 13) =
  11. ('H', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', '!', '\n');
  12. for (c: char in message) {
  13. // TODO: u8 should probably have an implicit cast to i32.
  14. Cpp.putchar((c as u8) as i32);
  15. }
  16. // TODO: Use a loop over a string literal instead. Requires IndexWith support
  17. // for str.
  18. //
  19. // let message: str = "Hello world!\n";
  20. // for (c: char in message) {
  21. // Cpp.putchar((c as u8) as i32);
  22. // }
  23. }
  24. // Demonstrate passing a null-terminated string to a C++ function.
  25. fn HelloStdio() {
  26. // TODO: There should be a better way to interact with functions that expect a
  27. // null-terminated string.
  28. Cpp.puts(Cpp.std.data("Hello world!\0"));
  29. // TODO: Requires variadic function support.
  30. // Cpp.printf("Hello world!\n\0");
  31. }
  32. // Demonstrate passing a string as a void pointer to a C++ function.
  33. fn HelloWrite() {
  34. let s: str = "Hello world!\n";
  35. Cpp.write(1, Cpp.std.data(s), Cpp.std.size(s));
  36. }
  37. fn HelloIostreams() {
  38. Cpp.std.cout << "Hello world!\n";
  39. }
  40. fn Run() {
  41. HelloPutchar();
  42. HelloStdio();
  43. HelloWrite();
  44. HelloIostreams();
  45. }