顯示具有 Compiler 標籤的文章。 顯示所有文章
顯示具有 Compiler 標籤的文章。 顯示所有文章

2020年9月3日 星期四

Makefile 筆記 (2)

Makefile 範本 (OS: Linux)

    這個 Makefile 有結合 .c 跟 .cpp 檔案, 並且使用一些字串處理 function。
    # gcc compiler 參數
    CC      := gcc
    CFLAGS  := -g -Wall -Werror -std=c99
    # g++ compiler 參數
    CXX     := g++
    CXXFLAG := -Wall -Werror -std=c++17


    # 宣告 source 資料夾
    SRC_DIRS = ./source
    # 把 source 資料夾裡的 cpp 跟 c 全部找出來
    SRCS := $(shell find $(SRC_DIRS) -name "*.cpp" -or -name "*.c")
    # 取檔名並把副檔名加上 .o
    OBJS := $(addsuffix .o,$(notdir $(SRCS))) main.o

    # include 參數 (適用於多個 include 資料夾, 成果會是 gcc -I/dir1 I/dir2)
    INC_DIRS  := ./include 
    INC_FLAGS := $(addprefix -I,$(INC_DIRS))

    all: program

    program: $(OBJS)
        $(CXX) $(CXXFLAG) $(OBJS) -o $@ 

    main.o: main.cpp
        $(CXX) $(INC_FLAGS) $(CXXFLAG) -c $< -o $@

    # .cpp.o 找 .cpp 編譯
    %.cpp.o: $(SRC_DIRS)/%.cpp
        $(CXX) $(INC_FLAGS) $(CXXFLAG) -c $< -o $@

    # .c.o 找 .c 編譯
    %.c.o: $(SRC_DIRS)/%.c
        $(CC)  $(INC_FLAGS) $(CFLAGS) -c $< -o $@

    .PHONY: clean

    clean:
        rm -rf ${OBJS} program
相關文章 :

2020年5月3日 星期日

Makefile 筆記 (1)

Makefile 範本 (OS: Windows)

    教學網路上很多,這裡記錄下我目前測試程式碼的 Makefile
    # 通用編譯參數
    CC     = gcc
    CFLAGS = -g -Wall

    # Objects = 為要與 main 連結的 .o 檔
    OBJECTS = hello.o pointer.o unsignedChar.o struct.o
    SOURCE_PATH  = source/
    INCLUDE_PATH = include/

    program: main.o ${OBJECTS}
        ${CC} ${CFLAGS} -o program.exe main.o ${OBJECTS}

    # 告訴編譯器 在當前目錄下找 main.c
    main.o: main.c
        $(CC) -I$(INCLUDE_PATH) $(CFLAGS) -c $<

    # 告訴編譯找 在 source/ 找 %.c 在 include/ 找 %.h
    %.o: $(SOURCE_PATH)%.c $(INCLUDE_PATH)%.h
        $(CC) -I$(INCLUDE_PATH) $(CFLAGS) -c $<

    clean:
        del main.o ${OBJECTS} program.exe

-I$(INCLUDE_PATH)

    這個是告訴程式碼在 include 時可以在這個目錄找,所以我的 main.c 在 include 時能如下,而不用#include "include/hello.h"
    #include "hello.h"
    #include "struct.h"
    #include "pointer.h"
    #include "pthread.h"
    #include "unsignedChar.h"
相關文章 :

2020年4月19日 星期日

C 語言 - #ifndef

#ifndef 用途

  • 在 .h 檔確保只會被編譯一次
  •     #ifndef HELLO_H // 有些人會定義成 _HELLO_H_
        #define HELLO_H // 但目的就是不會被重複編譯
    
        #include <stdlib.h>
    
        int helloIntro(char** str);
        int main() __attribute__((weak));
    
        #endif

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

Popular Posts