攝影師:Christopher Welsch Leveroni: https://www.pexels.com/zh-tw/photo/33152970/

Structures, Functions and Recursive Dependency

此篇介紹 C/C++ 結構定義與函式宣告的使用原則、recursive dependency 的解決方式,以及 complete usage 與 pointer usage 在實務設計上的考量。

關於這篇也是因為在前團隊累積了不少血淚才整理出的(到底多慘XD)技術含量不多,但還是有包含一點點當時領悟到的設計觀念。

Structure 的定義與使用

在 C/C++ 中,使用 structure(結構)時,必須遵循 define and use 原則:先定義結構,再使用該結構作為成員型別。

Define and use

假設 a.h 包含兩個結構:employee 與 occupation。

示範結構定義順序錯誤的情況:

struct employee {
    char name[32];
    unsigned int id;
    struct occupation oc;
};

struct occupation {
    char name[32];
    unsigned int id;
};

由於 employee 的成員 oc 使用了 struct occupation,但 occupation 的完整定義出現在後面,因此編譯器無法確定 oc 的大小,導致編譯錯誤。

就是要先定義才可以用啦,有些是 independent structure(獨立結構)、有些是 dependent structure(相依結構),如果和其他結構相依,至少要讓 compiler 知道這名詞指什麼,對吧!

如果要直接使用另一個結構作為成員,就得先知道它的完整定義;如果只是透過 pointer 參照,那先讓 compiler 知道這個型別存在就可以了。

假設我希望用前者,也就是直接使用,那正確方式就是先定義獨立結構,再定義相依結構:

struct occupation {
    char name[32];
    unsigned int id;
};

struct employee {
    char name[32];
    unsigned int id;
    struct occupation oc;
};

編譯器在處理 employee 時,便已經知道 occupation 的完整定義。

Function 的宣告與使用

函式一樣按照 declare and use 原則:在呼叫函式之前,編譯器必須已經取得該函式的宣告。

Declare and use

int foo(void);

int main(void) {
    return foo();
}

int foo(void) {
    return 10;
}

上述程式碼可以正常編譯,因為 foo() 的宣告出現在呼叫之前,即使函式定義位於後面也沒有問題。

在 header file 的相關介紹中,有稍微提過函式的宣告與定義具有不同用途,這邊再次整理:

  • Function declaration:提供函式名稱、回傳型別及參數資訊
  • Function definition:提供函式的實際實作
  • Function call:呼叫函式執行對應功能

Function definition 與 linking

函式宣告與定義不一定需要出現在同一個 source file。

例如:

a.c

int foo(void) {
    return 10;
}

b.c

int foo(void);

int main(void) {
    return foo();
}

b.c 只有 foo() 的宣告與呼叫,沒有函式定義,仍然可以獨立編譯成 object file。

這是因為編譯與連結是不同的階段:

  • Compilation:編譯器根據函式宣告檢查呼叫方式,並產生 object file。
  • Linking:連結器(linker)負責解析函式參照,找到對應的函式定義。

例如:

gcc -c a.c -o a.o
gcc -c b.c -o b.o
gcc a.o b.o -o app

前兩個指令分別編譯 source files,最後再連結為執行檔。

如果 foo() 沒有對應的函式定義,通常仍可完成個別 source file 的編譯,但在連結階段會發生 undefined reference error。

使用 Header file 提供宣告

在實際專案中,通常會將共用的函式宣告放在 header file,避免每個 source file 都要自行撰寫宣告。

a.h

#ifndef A_H
#define A_H

int foo(void);

#endif

a.c

#include "a.h"

int foo(void) {
    return 10;
}

b.c

#include "a.h"

int main(void) {
    return foo();
}

b.c 透過 #include "a.h" 取得 foo() 的宣告,符合 declare and use 原則。

Recursive dependency

Recursive dependency(遞迴相依)是指兩個結構互相依賴對方的完整定義,導致無法決定正確的定義順序。

在理解這個概念之前,需要先區分結構的兩種使用方式。

Pointer usage 與 complete usage

假設 employee 包含四個成員:

struct employee {
    char name[32];
    unsigned int id;
    struct designation des;
    struct occupation *oc;
};

其中 des 是 complete usage(完整使用),而 *oc 是pointer usage(指標使用),兩者的差異在於編譯器是否需要知道結構的完整大小。

Complete usage 需要完整結構定義,因為必須知道成員實際占用的記憶體大小;而 pointer usage 不需要,只需知道該結構型別的存在就好。

Structure 的大小

編譯器必須能夠計算結構的大小,因此需要知道每個成員的大小。

以前面的 employee 為例,假設:

  • name:32 bytes
  • id:4 bytes
  • designation:20 bytes
  • oc:4 bytes(32-bit 環境中的指標)

合計是 60 bytes(不計 padding)

在常見的 64-bit 環境中,指標通常為 8 bytes,而 32-bit 環境中通常為 4 bytes。實際大小仍取決於平台及資料模型。

Recursive dependency 的問題

假設 employee 和 occupation 都以 complete usage 的方式包含對方:

struct employee {
    char name[32];
    unsigned int id;
    struct occupation oc;
};

struct occupation {
    char name[32];
    unsigned int id;
    struct employee emp;
};

struct employee 需要 occupation 的完整大小,struct occupation 需要 employee 的完整大小。

無論先定義哪個結構,都會遇到另一個結構尚未完成定義的問題,因此無法編譯。

一般錯誤訊息會被標記為:

field 'oc' has incomplete type

這表示編譯器無法取得該成員型別的完整定義,因此無法確定它的大小。

解決 Recursive dependency

可以透過 forward declaration(前向宣告) 與 pointer usage 解決。

Forward declaration

Forward declaration 用來先宣告結構型別的存在,而不提供完整定義。總而言之就是先再前面寫好 struct occupation;,先宣告結構型別的存在,此時 struct occupation 屬於 incomplete type(不完整型別)。

編譯器雖然尚未知道它的完整大小,但已經可以宣告指向該結構的指標。

使用 Pointer Usage 打破相依關係

struct occupation;

struct employee {
    char name[32];
    unsigned int id;
    struct occupation *oc;
};

struct occupation {
    char name[32];
    unsigned int id;
    struct employee emp;
};

employee 使用 struct occupation *oc,不需要知道 occupation 的完整大小。employee 的完整定義完成後,occupation 就能直接使用 struct employee emp。

因此,原本互相依賴完整結構定義的問題,就能透過指標與前向宣告解決。

forward declaration 並不能讓 incomplete type 直接作為一般非指標成員。若要使用 complete usage,仍然需要先取得完整結構定義。

在設計資料結構時,會盡量避免不必要的 recursive dependency 啦。但實務上還是要看需求模型,若確實需要相互參照,就使用前面提及的 forward declaration 與 pointer usage。


一般來說,會先依據資料的擁有關係及生命週期決定。需要直接包含資料就選 complete usage,而需要參照其他物件、共享資料或處理循環相依的話,建議 pointer usage。

講是這樣講,但實務上經常看到 pointer usage,尤其是 C 語言的系統程式設計與大型專案。但不是因為 pointer usage 比 complete usage 高級,主要是因為提供了更大的設計彈性。

我目前整理到的基本上有以下考量:

  • 結構成員使用 pointer
    • 共享同一份資料:多個物件可以參照同一個結構,不需要各自保存一份副本。
    • 支援 linked list、tree 等動態資料結構。
    • 搭配 forward declaration,降低型別之間的相依,可以隱藏實作細節並減少 header file 的依賴。
  • 函式參數使用 pointer
    • 避免傳值時複製大型結構:傳遞指標通常比傳遞整個大型結構更有效率(這一點也常常是設計考量)。
    • 允許函式直接修改原始物件。

實務上我自己是沒有分很細(抱歉XDDD),關於避免複製大型結構那塊我之前面試有被電過,所以有點被制約了哈哈。


再給個例子好了,假設正在設計 employee:

struct occupation {
    int id;
    char title[32];
};

struct employee {
    int id;
    struct occupation *oc;
};

如果多名員工可以共享同一份 occupation 資料,pointer usage 就相當合理。

但如果 occupation 是每個員工獨立擁有的小型資料,而且應該與 employee 一起存在:

struct employee {
    int id;
    struct occupation oc;
};

complete usage 反而更單純,不需要額外管理指標的有效性與生命週期。

另外還有一種區別,例如:

void update_employee(struct employee *emp);

這是函式參數使用指標,主要是避免複製結構並允許修改原始物件;它和結構成員應該使用 complete usage 還是 pointer usage,是兩個不同的設計問題。

在一些大型系統中,通常會需要先理解 pointer usage,因為它廣泛應用於系統 API、資料結構及記憶體管理。

但設計自己的 struct 時,如果資料天生屬於該物件,生命週期一致,就可以優先考慮 complete usage;只有需要共享、間接參照、動態配置或解除相依時,再選擇 pointer usage。

(不過之前我在設計函式庫是公開介面,幾乎都用 pointer,所以我自己也拿不太準……畢竟還要考量到封裝與介面穩定性的設計需求)

另外,在大型專案中,如果結構已經公開給其他模組使用,兩種方式互相修改都可能影響大量程式碼,甚至破壞 ABI 相容性,所以先把資料模型與擁有權設計清楚非常重要。

之後我要找時間補一下相關知識,搞不好會再回來更新這一篇的設計考量~

讓我知道你在想什麼!