2020年4月19日 星期日

C 語言 - 編譯多個含有 main function 的 C code

編譯多個含有 main function 的 C code


    理論上是不行,GCC 無法自行繞過某某函式去編譯,通常是給條件去讓編譯器來達到 "只有一個你想要的 main function" 編譯目的。有人會問為什麼會有多個 main function,我想多半是因為想 Debug。

1. 利用 #ifdef

  • other.c
  •     #ifdef DEBUG
        int main ()
        {
            return 0;
        }
        #endif
  • gcc
  •     gcc -DEBUG other.c -o other.x

2. 利用 __attribute__((weak))

  • other.h ( __attribute__((weak)) 只能在宣告 function 時作 )
  •     int main() __attribute__((weak));
  • other.c
  •     int main ()
        {
            return 0;
        }

參考資料 :
https://stackoverflow.com/questions/35510670/compile-c-code-without-its-main-function

Related Posts:

  • C 語言 - CLI ( Command Line Interface ) 設計 (1)CLI 命令列介面     在設計 CLI 的程式時,最好的方法是遵從 IEEE Std 1003 ( POSIX ) 對 program 的 command-line options 之規範。所以用 getopt 去做 parse command-line 是最簡單的,有一點要注意的是 GNU 提供的 getopt 支援 " -- ",這個 PO… Read More
  • C 語言 - size_t 及各個常見類型 typedef unsigned int size_t // 通常定義在 stddef.h int8 : -128 ~ 127 int16 : -32768 ~ 32767 int32 : -2147483648 ~ 2147483647 int64 : -9223372036854775808 ~ 9223372036854775807 uint8 : … Read More
  • C 語言 - struct array 初始化 ( Initializing array of structures ) 初始化 struct array struct student { char* name; int grade; int id; }; 1. 依照當初宣告的順序 struct student myStudents[] = { {"Henry", 3, 1}, {"Marry", 3, 2} }; 1. 依照當初宣告的名子 … Read More
  • C 語言 - #ifndef #ifndef 用途 在 .h 檔確保只會被編譯一次 #ifndef HELLO_H // 有些人會定義成 _HELLO_H_ #define HELLO_H // 但目的就是不會被重複編譯 #include <stdlib.h> int helloIntro(char** str); int main() __attribute__((weak)); #endif … Read More
  • C 語言 - warning: left shift count >= width of type warning: left shift count >= width of type     一般來說,就是 shift 的 bit 大於資料型態的 bit 數。但有時使用 unsigned long 仍然會出錯,因為 unsigned long 會依照系統的不同,有時是 32 bit 有時是 64 bit,所以這時用 unsigned long long 較為安全 ( 保證 64 bit… Read More

0 意見:

張貼留言

Popular Posts