Hello World
一個簡單的 Hello, World 程式,沒有錯誤檢查:
#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; 
}
並通過錯誤檢查:
#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; 
}
編譯並執行
如果上面顯示的程式碼(任一版本)儲存在檔案 hello.c 中,那麼你可以使用 c99 或 make 將程式碼編譯到程式 hello 中 。例如,在嚴格遵守 POSIX 的模式下,理論上你可以使用以下命令編譯和執行程式:
$ make hello
c99 -o hello hello.c
$ ./hello
Hello, World
$
大多數實際的 make 實現將使用不同的 C 編譯器(可能是 cc,也許是 gcc,clang,xlc 或其他名稱),並且許多將使用更多選項到編譯器。顯然,你只需在命令列上鍵入 make 直接執行的命令即可。