forked from ccccourse1/sp110b
-
Notifications
You must be signed in to change notification settings - Fork 0
week12.md
feliciachou edited this page Jun 16, 2022
·
1 revision
simple Hello, World program without error checking:
#include <unistd.h> /* For write() and STDOUT_FILENO */
#include <stdlib.h> /* For EXIT_SUCCESS and EXIT_FAILURE */
int main(void) {
char hello[] = "Hello, World\n";
/* Attempt to write `hello` to standard output file */
write(STDOUT_FILENO, hello, sizeof(hello) - 1);
return EXIT_SUCCESS;
}
And with error checking:
#include <unistd.h> /* For write() and STDOUT_FILENO */
#include <stdlib.h> /* For EXIT_SUCCESS and EXIT_FAILURE */
int main(void) {
char hello[] = "Hello, World\n";
ssize_t ret = 0;
/* Attempt to write `hello` to standard output file */
ret = write(STDOUT_FILENO, hello, sizeof(hello) - 1);
if (ret == -1) {
/* write() failed. */
return EXIT_FAILURE;
} else if (ret != sizeof(hello) - 1) {
/* Not all bytes of `hello` were written. */
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
Compiling and running
If the code shown above (either version) is stored in file hello.c, then you can compile the code into a program hello using either c99 or make. For example, in a strictly POSIX compliant mode, you might in theory compile and run the program using:
$ make hello
c99 -o hello hello.c
$ ./hello
Hello, World
$
Most actual make implementations will use a different C compiler (perhaps cc, perhaps gcc, clang, xlc or some other name), and many will use more options to the compiler. Clearly, you could simply type the command that make executes directly on the command line.
References : https://riptutorial.com/posix/example/15987/hello-world