c++中如何包含cpp文件?
来源:百度知道 编辑:UC知道 时间:2024/07/05 06:17:49
--------------------Configuration: void - Win32 Debug--------------------
Compiling...
file1.cpp
file2.cpp
Linking...
file2.obj : error LNK2005: "double __cdecl add(double,double)" (?add@@YANNN@Z) already defined in file1.obj
Debug oid.exe : fatal error LNK1169: one or more multiply defined symbols found
执行 link.exe 时出错.
void.exe - 1 error(s), 0 warning(s)
--------file1.cpp--
double add(double a, double b)
{
return a + b;
}
-----file2.cpp
#include "file1.cpp"
#include <iostream.h>
void main()
{
double a,b;
double e,f;
a = 3;
b = 2;
e = add(a,2);
f = add(b+1,2);
cout<<e<<"\t"<<f<<endl;
}
如果file2.cpp 调用file1.cpp 就不好使就会出现这个问题.
如果改成file1.h file2.cpp 就可以调用/
那么我应该怎么正确调用file1.cpp 加载到file2.cpp里呢?
Compiling...
file1.cpp
file2.cpp
Linking...
file2.obj : error LNK2005: "double __cdecl add(double,double)" (?add@@YANNN@Z) already defined in file1.obj
Debug oid.exe : fatal error LNK1169: one or more multiply defined symbols found
执行 link.exe 时出错.
void.exe - 1 error(s), 0 warning(s)
--------file1.cpp--
double add(double a, double b)
{
return a + b;
}
-----file2.cpp
#include "file1.cpp"
#include <iostream.h>
void main()
{
double a,b;
double e,f;
a = 3;
b = 2;
e = add(a,2);
f = add(b+1,2);
cout<<e<<"\t"<<f<<endl;
}
如果file2.cpp 调用file1.cpp 就不好使就会出现这个问题.
如果改成file1.h file2.cpp 就可以调用/
那么我应该怎么正确调用file1.cpp 加载到file2.cpp里呢?
可以加一个file1.h
里面加这内容:
double add(double a, double b);
就以上一句就可以。
然后在file2.cpp中,这样写:
#include <iostream.h>
#include "file1.h"
void main()
{
double a,b;
double e,f;
a = 3;
b = 2;
e = add(a,2);
f = add(b+1,2);
cout<<e<<"\t"<<f<<endl;
}
/////////////
这样,file2.cpp就可以使用file1.cpp中定义的函数了
把 file1.cpp里的函数原型写在 file2.cpp上面就可以。 不要include
或者你把file1.cpp从工程中去掉也可以
建立一个file1.h 把cpp里的文件全部在里面声明 如下
double add(double a, double b) ;
然后在fille2里将 file1.h 包含进去 如下
#include"file1.h"
.h是 头文件
.cpp 是源文件
c++中。通常 将struct class #define typedef function 等的定义放到头文件中,
而将 成员声明 和 function实现 类实现 放入cpp中。
h和cpp中同时可以使用include包含头文件,但是通常有个习惯,就是尽量不要在.h文件中include非必须的其他.h文件。
也就是说,当.h中的内容(各种声明)用到了T* t那么我们 没有必要 #include "t.h",只需要在。h中