iT邦幫忙

DAY 6
0

21世紀C語言實作及感想系列 第 6

21世紀C語言之6 :Here Document

請問沒有存檔的源碼(.c), 可以編譯成執行檔嗎?

這是筆者對Here Document 用途上的另一個理解!

Here Document可參考wiki,http://en.wikipedia.org/wiki/Here_document.

筆者的shell功力不是很好,還好有範例可以理解。

我們先用wiki的範例理解一下Here Document。

tr 是一個標準的POSIX指令,功能是轉換。

筆者在MINGW 下做練習,

大寫變小寫

$ tr A-Z a-z <<< IRONMAN7
ironman7

小寫變大寫

$ tr a-z A-Z <<< 'one two three four five'
ONE TWO THREE FOUR FIVE

換個寫法,仍是小寫變大寫

FOO="one two three four five"

$ tr a-z A-Z <<< $FOO

$ tr a-z A-Z <<< $FOO
ONE TWO THREE FOUR FIVE

$ cat << EOF

Working dir $PWD
EOF
Working dir /c/emacs

$ tr a-z A-Z <<- END_TEXT

one two three
uno dos tres
END_TEXT
ONE TWO THREE
UNO DOS TRES

所以Here Document,是由**<<-,<<< 讓user輸入多行文字,**

本書作者,巧思一個範例,

$ go_libs="-lm"

$ go_flags="-g -Wall -include stdio.h -O3"

$ alias go_c="gcc -xc '-' $go_libs $go_flags"

$ go_c << '---'

int main() {printf("Hello from the command line. \n");}

$ ./a
Hello from the command line.

這就回答了 筆者前面提到的問題,

我的源碼並沒有存檔,但是可以編譯成執行檔。

Here Document 就是在命令列模式下,讓user可以輸入多行文字的小工具。

另外,作者還有個小技巧 ,

The Unified Header,萬用表頭檔,

他的意思是,如果有常用的幾個表頭檔,不要寫在源碼裏,真接獨立出來,用參數-include 來包含,

這有兩個好處,一是表頭檔(.h)永遠只寫一份, 源碼檔(.c)都去把它含入,即使這個源碼檔並沒用到。

如 你可以用一個allheads.h,

#include <math.h>
#include <time.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <gsl/gsl_rng.h>

筆者覺得挺實用的。

這本21世紀的C, 很像是一本老鳥的寫作秘技公開,覺得作者的巧思挺讓人有驚喜的。


上一篇
21世紀C語言之5 :makefile
下一篇
21世紀C語言之7 :好朋友->指標
系列文
21世紀C語言實作及感想30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言