function

Can we write a function in different.cpp file?? if yes then what we write in the main file to connect the second one. please suggest.
Thanks.
Before you can call a function you need to declare it. Function declarations are often put into header files (.h) but you can put them directly inside a source file (.cpp) if you want to.

main.cpp
1
2
3
4
5
6
7
8
9
// Function declaration. This tells the compiler that f is a function
// with return type void which takes no arguments.
void f();

int main()
{
	f(); // Calls function f. This works thanks to
	     // the function declaration on line 3.
}

different.cpp
1
2
3
4
5
6
7
8
#include <iostream>

// Function definition. This specifies what 
// will happen when the f function is called.
void f()
{
	std::cout << "f() was called.\n";
}

There is no automatic connection between main.cpp and different.cpp. It is up to you (and to the tools that you're using) to make sure both files are complied (separetly without knowledge of each other) and then linked together to form the final executable file. If you use an IDE this is usually done by placing both files in the same project.
Last edited on
http://www.cplusplus.com/forum/general/113904/#msg622055
http://www.cplusplus.com/doc/tutorial/functions/ (declaring functions)

to be able to call the function, only the prototype is needed.
the implementation may be in another source file, that's linked in the link stage.
Topic archived. No new replies allowed.