跳轉到內容

GNU C 編譯器內部/GCC 技巧 4 1

來自華夏公益教科書

每個結構的 toString() 方法,如 Java 中的

[編輯原始碼]

從函式中呼叫程式碼塊,如 Ruby 中的

[編輯原始碼]

Linux 中的列表實現允許在列表的每個元素上呼叫程式碼塊

pagelist.c:

       list_for_each_prev(pos, head) {
                struct nfs_page *p = nfs_list_entry(pos);
                if (page_index(p->wb_page) < pg_idx)
                        break;
       }

list_for_each_prev 將方括號中的程式碼作為引數。訣竅是使用一個宏,它會擴充套件到一個 for() 迴圈,其主體成為方括號中的程式碼。這個專案的目的是允許程式設計師在函式呼叫中使用程式碼塊。

返回結構體時解引用函式結果

[編輯原始碼]

C 允許你在函式返回指向結構的指標時解引用函式的返回值

 get_struct()->field=0;

如果函式返回的是結構體,而不是指向結構體的指標,則會生成編譯時錯誤

 get_struct().field=0;
 > request for member `field' in something not a structure or union

此擴充套件解決了解引用作為返回值的結構體的問題。

使用函式初始化變數

[編輯原始碼]

當定義並初始化一個變數時,初始化器是常量。如果你嘗試使用函式,無論該函式是什麼,你都會收到錯誤資訊

 int getint() { return 1; }
 int i=getint();
 > initializer element is not constant

當使用一個變數時,呼叫它初始化的函式。

函式引數的預設值,如 C++ 中的

[編輯原始碼]
 void func(int a=0) {
   printf("a=%d\n", a);
 }
 int main() {
   func();
 }
 > syntax error before '=' token

C++ 中的引用引數

[編輯原始碼]
 void test(int &a, int &b);
 int x,y;
 test(x,y);


目標檔案中的 GCC 開關

[編輯原始碼]

目標檔案中的 GCC 開關用法:/usr/local/bin/paster serve [選項] CONFIG_FILE [啟動 | 停止 | 重啟 | 狀態] 服務所描述的應用程式

如果給出啟動/停止/重啟,它將啟動(正常操作)、停止(--stop-daemon)或執行兩者。你可能還想使用 ``--daemon`` 來停止。

選項

 -h, --help            show this help message and exit
 -v, --verbose
 -q, --quiet
 -nNAME, --app-name=NAME
                       Load the named application (default main)
 -sSERVER_TYPE, --server=SERVER_TYPE
                       Use the named server.
 --server-name=SECTION_NAME
                       Use the named server as defined in the configuration
                       file (default: main)
 --daemon              Run in daemon (background) mode
 --pid-file=FILENAME   Save PID to file (default to paster.pid if running in
                       daemon mode)
 --log-file=LOG_FILE   Save output to the given log file (redirects stdout)
 --reload              Use auto-restart file monitor
 --reload-interval=RELOAD_INTERVAL
                       Seconds between checking files (low number can cause
                       significant CPU usage)
 --status              Show the status of the (presumably daemonized) server
 --user=USERNAME       Set the user (usually only possible when run as root)
 --group=GROUP         Set the group (usually only possible when run as root)
 --stop-daemon         Stop a daemonized server (given a PID file, or default
                       paster.pid file)

[app:main] use = egg:PasteEnabledPackage option1 = foo option2 = bar

[server:main] use = egg:PasteScript#wsgiutils host = 127.0.0.1 port = 80 sudo update-rc.d startup.sh defaults

執行時的型別資訊

[編輯原始碼]

C 語言中沒有執行時可用的型別資訊。這個想法是允許程式在執行時獲取結構體欄位的名稱和偏移量、列舉宣告的符號名稱等等。例如,而不是寫

  enum tree_code code;
  ...
  switch (code) {
    case VAR_DECL:
      printf("VAR_DECL\n");
      break;
    case BLOCK:
      printf("BLOCK\n");
      break;
    ...
  }

可以寫

  printf("%s\n", type_info(code).name);
前一個: C 中的函式過載 GCC 技巧 下一個: 連結
華夏公益教科書