作者flax00298 (NI)
看板C_and_CPP
標題[問題] include funcitons and classes
時間Fri Apr 12 14:05:33 2013
想要問一個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
推 legendmtg:搞清楚什麼是宣告 什麼是定義就懂了 04/12 14:35
→ MOONRAKER:阿你不是有用#ifndef guard了怎麼還會重覆定義 04/13 16:28
推 iamstudent:如果多個c/cpp引用到該head檔,就會出現多個函數實體 04/13 16:59
→ iamstudent:linker會找到不只一個該名稱的函數實體 04/13 17:00
推 legendmtg:宣告可以重覆 定義只能有一次 04/13 22:00