如何在C++程序中包含自定义文件

3
如何在文件1中包含文件2。我需要在文件2中做哪些更改。
文件1
 #include <iostream>

 using namespace std;

int main()
{
cout<<"Hello World";

return 0;
}

文件2

 int otheFun()
 {
   cout<<"Demo Program";
   return 0;
 }

1
问题没有意义。你不能在一个程序中有两个程序。功能将是什么?哪个“main”会执行? - Lightness Races in Orbit
1
你需要解释你想要达到的效果。你想要发生什么? - David Schwartz
2个回答

11

你不应该将cpp文件包含到另一个cpp文件中。
此外,C++程序只能有一个main()函数。
如果你想要处理一个具有多个文件的程序,你需要像这样做:

file2.cpp

#include <iostream>
#include "file2.h"


int printHelloWorld()
{
    std::cout<<"Hello World";

    return 0;
}

file2.h

 #ifndef FILE2_H    <----Lookup Inclusion Guards on google, this is important concept to learn.
 #define FILE2_H

 int printHelloWorld();

 #endif //FILE2_H

file1.cpp

#include <iostream>
#include "file2.h"


 int main()
 {
     std::cout<<"Demo Program";
     printHelloWorld();
     return 0;
 }

创建头文件,然后再包含怎么样? - sandbox
@沙盒:包括什么?你想实现什么? - Lightness Races in Orbit
学习创建头文件...例如:file2.h - sandbox

1
我需要在文件2中进行哪些更改?
#include <iostream>

using namespace std;

int main()
{
   cout << "Hello world";
   cout << "Demo Program";
}

3
应该按照原帖作者的要求去做,虽然你忘记了“使用讽刺”的部分。 - ssube
1
@peachykeen:我知道我忘记了“某些东西”……! - Lightness Races in Orbit
我可以提出另一个更改吗? - Manuel Selva

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接