[問題] include funcitons and classes

看板C_and_CPP作者 (NI)時間11年前 (2013/04/12 14:05), 編輯推噓3(302)
留言5則, 3人參與, 最新討論串1/2 (看更多)
想要問一個C++的問題: 當一個header file裡面宣告並且定義了一個function: // test.h #ifndef TEST_H #define TEST_H int func() {return rand();} #endif 接下來有兩個.cpp都include test.h,compiler在link的時候 會給redefinition of func()的error。 但是如果是class而不是function: // test.h #ifndef TEST_H #define TEST_H class A {}; #endif 兩個cpp也都inlcude test.h的情況下就不會有error 這樣的話在link的時候,在兩個.o裡面應該也都有class的宣告跟定義。 請問為什麼不會有redefinition的問題呢? 先謝謝各位不吝賜教的大大:) -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 140.112.171.142

04/12 14:35, , 1F
搞清楚什麼是宣告 什麼是定義就懂了
04/12 14:35, 1F

04/13 16:28, , 2F
阿你不是有用#ifndef guard了怎麼還會重覆定義
04/13 16:28, 2F

04/13 16:59, , 3F
如果多個c/cpp引用到該head檔,就會出現多個函數實體
04/13 16:59, 3F

04/13 17:00, , 4F
linker會找到不只一個該名稱的函數實體
04/13 17:00, 4F

04/13 22:00, , 5F
宣告可以重覆 定義只能有一次
04/13 22:00, 5F
文章代碼(AID): #1HPwGlnC (C_and_CPP)
文章代碼(AID): #1HPwGlnC (C_and_CPP)