# 最簡單的 c 程式 2022 ###### tags: `C LANGUAGE` `output queue` <style> .blue { color: blue; } .bgblue { color: blue; font-size: 24px; font-weight: bold; } .red { color: red; font-size: 24px; font-weight: bold; } h1 {text-align: center;} </style> Author: WhoAmI Date: 20220726 Copyright: CC BY-NC-SA 若您有寶貴的意見,改進或建議歡迎 email 給本人, 大專以上教師若要教學使用可自行免費使用修改當教材給學生使用 WhoAmI e-mail: kccddb@gmail.com :::success 如果您能力夠請 贊助 (可用信用卡): If possible, please donate Taiwan Fund for Children and Families (TFCF) : [財團法人台灣兒童暨家庭扶助基金會](https://https:www.ccf.org.tw/) ::: ![](https://i.imgur.com/tK3lSZb.png) <font color="#f00">**bugs 除不盡春風吹又生**</font> <h1> 千里之行始於足下</h1> **** 養成良好的程式設計習慣, <font color="#f00">資料型態最好依照 man page, 如此日後才方便移植至其他系統!</font> 小故事: 以前老總看到一位於上市公司研發部 "五年" 經驗的求職者, 本來要請他來面談, 結果 我收到 他的email 來的作品(程式), 看過就婉謝了. Why? **還有 10 多年經驗的研發, c, c++ 綜合體~變形金剛???** 另一正面的故事, 我朋友公司來了一位外文系的有心學, 我朋友就教他, 最後 他成為團隊裡最強的研發人員. **養成良好的程式習慣** 本人擔任外面公司顧問多年, 深深覺得就算國立大學研究所資工相關科系畢業, **程式撰寫習慣欠佳**(1. 有點像寫作業! 2. 不太會用 Makefile 3. 作業系統觀念淪為考試用 4. warning 當正常 ) 業界大都要靠團隊合作, 習慣不好如何與別人配合, 日後新增修改如何處理? 有問題的程式碼沒註明 ###### Garbage Collection(GC) 養成設計師的壞習慣 (尤其會 java 的), 以前一位 研究生 用java, 我說不能如此寫, 請他試試 長期執行是否會 掛! 後來他說 真的掛!!!! ###### Critical Section lock un-lock 效能問題 ###### Variable has no initial value 有些 剛開機 可以, 但過陣子又不行 ###### memory leaks (這是嚴重的大問題, 時常與程式習慣與疏忽有關) ###### data type 錯誤( 32/64 bits 移植至 16bits) ###### volitile 不知其重要性 (尤其 單晶片, kernel driver, ...) ###### interrupt 處理方式不正確, 造成 有時 沒動作 ###### Thread safety, e.g., gethostbyname(), strtok(),... (See man page) ###### printf, cout 過分濫用, 不知其影響效能, c/c++ 混用 ###### 用 大 array 代替 malloc....真誇張, 不知他如何畢業的 ###### 練習看 man page --- **基本c 語言的資料可以參閱很不錯的文件(包含 簡單的 makefile)**: [Tim Love, ANSI C for Programmers on UNIX Systems](http://www-h.eng.cam.ac.uk/help/documentation/docsource/teaching_C.pdf) --- ![](https://i.imgur.com/nPq6i2N.jpg) [OnlineGDB](https://www.onlinegdb.com/) 可以練習 c, bash,... 善用: #define #ifdef #ifndef #define debug(x) x [Variadic Macros](https://gcc.gnu.org/onlinedocs/cpp/Variadic-Macros.html) gcc -Wall ... 行有餘力 學 gdb ![](https://i.imgur.com/6UDLvKm.jpg) ![](https://i.imgur.com/ft9gjlo.jpg) ![](https://i.imgur.com/04n6fsc.jpg) ![](https://i.imgur.com/bnO2bXZ.jpg) ![](https://i.imgur.com/WAfeUAT.jpg) ### 寫好網路程式除了網路基礎外, Object-oriented programming (OOP) 與 OS 的知識是必須的! [C 也可以寫的很OOP 簡單範例與簡易Makefile](https://hackmd.io/@pingulinux/c-oop) basic.c: ```c= /* * *Copyright (C) 2019 My-Company-Name *Version: 1.101 2019/01/01 *Authors: WhoAmI, <whomani@xxxgmail.com> * John, <john@xxxgmail.com> *Fixes: * John : 2018/01/01, Fixed warnings * WhoAmI: 2022/07/20 update * *Complie and Link: * gcc -Wall basic.c -o basic * *TODO: Homework, DUE DATE: 2019/01/01 *BUGS: *Based upon WHAT */ #define VARSTR1 "iloveyou" #define VARSTR2 "ilove" /* Declaration for printf() */ #include <stdio.h> /* Declaration for exit() Constant Explanation EXIT_SUCCESS successful execution of a program EXIT_FAILURE unsuccessful execution of a program */ #include <stdlib.h> /*Declaration for strlen(), strncmp()*/ #include <string.h> /*int strncmp(const char *s1, const char *s2, size_t n); strcmp() is not good! Why? (s1或 s2 結尾沒有 0 會如何?) */ int main(int argc, char *argv[]) { int i, j; size_t len; /*size_t represents the size of objects in bytes, see man strncmp() */ int answer; /* comments...*/ len=strlen(VARSTR2); answer = strncmp(VARSTR1 , VARSTR2, len); printf("Answer=%d\n", answer); //don't use "cout", Why? exit (0); /* exit(EXIT_SUCCESS) is better.*/ } ``` <font color="#f00">為什麼要 exit ?</font> shell script 幫助檢查執行結果 正確與否 ```shell #!/bin/bash #test command: ls ls echo $? if [ "$?" -ne "0" ]; then echo "error..." exit 1 fi exit 0 ``` 注意 檔案格式 要用 unix 格式 Makefile 也要用 unix 格式 dos2unix 可幫您轉換!!! 常用的工具程式 :::info strace- trace system calls and signals ldd - print shared object dependencies top - display Linux processes strip - discard symbols and other data from object files pstree - display a tree of processes 基本常用的工具請自行參閱網路上的文件例如 (ls, cp, rm, gcc, vim, cd, tar, gunzip, gzip, bzip2, grep, more, find...) ::: 這是一個 相當簡單的 c 程式, 但是有很多值得理解的問題 **Input Queue** ![](https://i.imgur.com/8HG6mxJ.jpg) **Output Queue 與多工輸入時共有的現象.** ![](https://i.imgur.com/tJxuRYf.jpg) ![](https://i.imgur.com/7XS1Thq.jpg) ![](https://i.imgur.com/ac8eEZs.jpg) 除了 output congestion 問題以外, 還有 不同 process 到 kernel 的同步 (synchronous) 問題! 這是一般讀者常忽略的問題! 例如 Google GO channels type 與 memory management 程式的設計考慮多CPU 的平行處理(例如 Google GO: Efficient parallel computation) *convolution 多CPU 例子(學過通訊的應該看得懂) :::info gcc 新的版本 可以用 multiline string (寫 CGI 程式很好用) ```c= #include <stdio.h> #include <stdlib.h> int main() { const char * poem = R"v0( 《老子》第六四章: 「合抱之木,生於毫末; 九層之臺,起於累土; 千里之行,始於足下 。」 )v0"; printf("%s",poem); exit(EXIT_SUCCESS ); } ``` ::: **運用 gcc Variadic Macros, 兩者有點小不同, 您執行看看就知道了.** ```c= #include <stdio.h> #include <stdlib.h> #define LONGSTRING(...) #__VA_ARGS__ int main(int argc, char argv[]){ const char *poem=LONGSTRING(《老子》第六四章:\n 「合抱之木,生於毫末; 九層之臺,起於累土; 千里之行,始於足下 。」); printf("%s\n",poem); exit(EXIT_SUCCESS); } ``` **do {...}while(0)** ```c= /* * do {...}while(0) * / #include <stdio.h> #include <stdlib.h> #include <errno.h> #define prn(x) do { perror("MSG:"); \ fprintf(stderr,"LINE %d %s",__LINE__,x);\ exit(EXIT_FAILURE);}while(0) int main(int argc, char *argv[]) { if(argc>1) prn(argv[1]); else exit(EXIT_SUCCESS ); } ``` SSH, telnet,... [MobaXterm ](https://mobaxterm.mobatek.net/download.html) 文字編輯: [Komodo Edit](https://www.activestate.com/products/komodo-ide/downloads/edit/) 沒有 Windows 就靠 vim ```c= #include <stdio.h> #include <stdlib.h> #ifdef Debug #define debug1(x) x #define release(x) #else #define debug1(x) #define release(x) x #endif int main(int argc, char *argv[]) { debug1(printf("debug version\n")); release(printf("release version\n")); exit(EXIT_SUCCESS); } ``` :::info ```c __FILE__ This macro expands to the name of the current input file, in the form of a C string constant. __LINE__ This macro expands to the current input line number, in the form of a decimal integer constant. __FILE__ and __LINE__ are useful in generating an error message to report an inconsistency detected by the program; the message can state the source line at which the inconsistency was detected. For example, ::: ``` ```c= fprintf (stderr, "Internal error: " "negative string length " "%d at %s, line %d.", length, __FILE__, __LINE__); ``` **HW:** ./basic happy day !!! 程式如何 輸出 happy day ? **HW:** [c language: function pointer, callback](https://hackmd.io/@pingulinux/function-pointer-callback) printf 設計方法: [stdarg, va_start, va_arg, va_end, va_copy - variable argument lists](https://www.man7.org/linux/man-pages/man3/stdarg.3.html) 過去教 大三網路程式設計最後一次作業(team work)---可以進行檔案續傳的 client/server, 讓同學 體會 穩定不容易 1. 可以網路連結斷線後續傳完成(要 wifi 可用, 測拔網路線, 蓋金屬蓋, 斷電, 不同網路頻寬,...) 2. 1Gbytes 以上 3. 具有 timeout 的機制, 特別是 send timeout 4. 不同 CPU byte order 的問題, 例如 little-endian <-->big-endian 5. TCP send N 次 recv 是N 次嗎? 一般來說不正確! 可能 M 次, N<M, N>M, N=M 都有可能 ![](https://i.imgur.com/32BmoZj.jpg) [how to use void ** pointer correctly?](https://stackoverflow.com/questions/9040818/how-to-use-void-pointer-correctly) **Abstract List** ![](https://i.imgur.com/GMmfNE5.jpg)