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?
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.
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.
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.
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.
void MyFunc();
#include "other.h" int main() { MyFunc(); }
#include "other.h" #include <iostream> void MyFunc() { std::cout << "Ohai from another .cpp file!"; std::cin.get(); }
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 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With