看板 C_and_CPP 關於我們 聯絡資訊
※ 引述《eliang ()》之銘言: : 在 C++ Primer 這本書裡, 提到 inline 函式應該定義在 header file 裡 : 書上說明原因如下: : An inline function may be defined more than once in a program as long as the : definition appears only once in a given source file and the definition is : exactly the same in each source file. By putting inline functions in headers, : we ensure that the same definition is used whenever the function is called : and that the compiler has the function definition available at the point of : call. : 我看不太懂它的意思...有沒有人可以解釋一下? : 我之前都比較習慣把函式定義放在 .cpp 檔, 函式宣告放 .h 檔 : 因為這樣程式碼感覺起來比較乾淨, 像是這樣: : // foo.h : class foo { : public: : int f(); : }; : // foo.cpp : inline int foo::f() { : // short statement... : } 既然要讓它 inline, 就把函式定義一起寫在 foo.h 中。 就是把你的 foo.cpp 檔的內容直接copy到 foo.h 檔原來的 內容後面。這樣一樣很乾淨啦。 : 可是我發現這樣寫 "有時候" 編譯會發生錯誤, 訊息大概就類似: : [Linker error] undefined reference to 'foo::f()' : 如果把 inline 去掉, 或照書上說的, 把定義改寫到 .h 檔, 就可以正常編譯, : 請問這是什麼原因? 謝謝!! 因為 inline 的本質就是可以讓編譯器在單獨編譯某個 使用到這個 inline function 的 source file的時候, 可以將整個 inline function 的定義插入並取代呼叫 inline function的那行敘述。你沒給他函式定義,它 怎麼做這個動作呢? 當然,你指定要 inline 編譯器不一定真能做到 inline, inline 只是吾人對編譯器的「建議」。但是好歹你要將 inline function 的定義透過 .h 檔 include 進來,不然, 編譯器根本沒機會幫你 inline. inline 的時機是定義簡短的函式。太長的、或是 virtual function 或是 recursive function 都不宜或不能 inline. -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 220.130.208.168
renderer:推 滿重要的 inline 概念 61.228.217.108 08/21
eliang:說明得很詳細,感謝!! 210.58.40.9 08/21