Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using multiple .cpp files in c++ program?

Tags:

c++

function

I recently moved from Java for C++ but now when I am writing my application I'm not interested in writing everything of the code in the main function I want in main function to call another function but this other function is in another .cpp file.

Let me explain better if you wouldn't understand:
I have one file: main.cpp inside it I have main function.

I have the second file: second.cpp inside I have a function called second() I want to call this function called second() from my main function..

Any help?

like image 728
Rakso Avatar asked Aug 09 '11 11:08

Rakso


People also ask

Can you have multiple cpp files?

You must use a tool called a "header". In a header you declare the function that you want to use. Then you include it in both files. A header is a separate file included using the #include directive.

How would you handle multiple common header files in different programs?

Including Multiple Header Files: You can use various header files in a program. When a header file is included twice within a program, the compiler processes the contents of that header file twice. This leads to an error in the program. To eliminate this error, conditional preprocessor directives are used.

How do we implement multiple source program files?

Split the program into three files, main. c, which contains main(), node. h, the header which ensures declarations are common across all the program, and hence is understood by the compiler, and node. c, the functions which manipulate the NODE structure.


2 Answers

You must use a tool called a "header". In a header you declare the function that you want to use. Then you include it in both files. A header is a separate file included using the #include directive. Then you may call the other function.

other.h

void MyFunc(); 

main.cpp

#include "other.h" int main() {     MyFunc(); } 

other.cpp

#include "other.h" #include <iostream> void MyFunc() {     std::cout << "Ohai from another .cpp file!";     std::cin.get(); } 
like image 151
Puppy Avatar answered Oct 05 '22 01:10

Puppy


You should have header files (.h) that contain the function's declaration, then a corresponding .cpp file that contains the definition. You then include the header file everywhere you need it. Note that the .cpp file that contains the definitions also needs to include (it's corresponding) header file.

// main.cpp #include "second.h" int main () {     secondFunction(); }  // second.h void secondFunction();  // second.cpp #include "second.h" void secondFunction() {    // do stuff } 
like image 23
Creat Avatar answered Oct 05 '22 02:10

Creat