简体   繁体   中英

How to include Custom files in C++ program

How to include file 2 in file 1. What changes I need to make in file 2.

file 1

 #include <iostream>

 using namespace std;

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

return 0;
}

file 2

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

You do not include cpp files in to another cpp files.
Also, a c++ program can have only one main() function.
If you are trying to play around with a program which has multiple files, You will need to have something like this:

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;
 }

What changes I need to make in file 2?

#include <iostream>

using namespace std;

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM