写了一段程序试了一下 声明try.h: #ifndef TRY_H_INCLUDED #define TRY_H_INCLUDED int add_two_number(int& a, int& b); #endif // TRY_H_INCLUDED 然后是定义try.cpp: #include "try.h" int add_two_number(int& a, int& b) { return a+b; } 然后是主程序: #include "try.h" #include using namespace std; int main() { int x1=1; int x2=2; int x3=add_two_number(x1, x2); cout<cout<} 可以一直不能运行啊 但是在主程序中只有加了#include "try.cpp"才可以运行 这是怎么回事呢? 谢谢了
S*I
6 楼
How do you compile your program?
【在 f******n 的大作中提到】 : 写了一段程序试了一下 : 声明try.h: : #ifndef TRY_H_INCLUDED : #define TRY_H_INCLUDED : int add_two_number(int& a, int& b); : #endif // TRY_H_INCLUDED : 然后是定义try.cpp: : #include "try.h" : int add_two_number(int& a, int& b) : {
t*n
7 楼
windows/linux?
【在 f******n 的大作中提到】 : 写了一段程序试了一下 : 声明try.h: : #ifndef TRY_H_INCLUDED : #define TRY_H_INCLUDED : int add_two_number(int& a, int& b); : #endif // TRY_H_INCLUDED : 然后是定义try.cpp: : #include "try.h" : int add_two_number(int& a, int& b) : {
d*o
8 楼
因为你只compile了主程序,没有compile并link try.cpp
【在 f******n 的大作中提到】 : 写了一段程序试了一下 : 声明try.h: : #ifndef TRY_H_INCLUDED : #define TRY_H_INCLUDED : int add_two_number(int& a, int& b); : #endif // TRY_H_INCLUDED : 然后是定义try.cpp: : #include "try.h" : int add_two_number(int& a, int& b) : {
you can separate declaration and implementation into .h and .cpp. and that makes sense if you collaborate with other programmers. if you are entirely on your own, nothing stops you from writing a gigantic main.cpp that has all the classes in it. you could use ide tools such as visual assist x to generate the duplicated function signatures. yes, if you compile **.cpp and link against **.obj. no, if you just compile your main.cpp. sometimes you will, esp if templates are involved.
if you use a lot of template classes, a single file (compilation unit) actually compiles faster, because the instantiation of duplicate templates are curtailed. if you happen to have CGAL, notice they use this kind of "all _compile.cpp" trick. if you observe a slow down in release mode, that also makes sense: the compile might be busy looking for opportunities to inline (a poor man's ltcg essentially...).