I've been studying C++ for a little while now and want to start getting into actual application/software development. The problem is I'm having a hard time figuring out some of the more practical aspects of how to exactly setup a project. My question today is if I have a function that is not being declared and defined in a standard class structure, where exactly should I, or is it most common to, declare and define it? Most tutorials you watch will declare a function in main.cpp, above main() and then define it below main() but I assume that is just for teaching purposes and not real world application. Should you just create function header and source files just as you would with classes?
You will need to declare (prototype) the function in a .h file, and then implement it in a .cpp file. Example:
main.cpp
:
#include "header.h"
int main()
{
// use the functions
printf("%f, %f", add(10, 10), sub(64, 2.8));
}
header.h
:
double add(double, double); // function declarations
double sub(double, double);
header.cpp
:
#include "header.h"
double add(double a, double b) // function implementations
{
return a + b;
}
double sub(double a, double b)
{
return a - b;
}
Yes, you can have the main cpp file along with separate header/source files for your own functions. Something like this:
/main.cpp
#include "myFunctions.h"
int main(){
printSum(5, 5);
return 0;
}
/myFunctions.h
#ifndef MYFUNCTIONS_H
#define MYFUNCTIONS_H
void printSum(int, int);
#endif
/myFunctions.cpp
#include "myFunctions.h"
void printSum(int num1, int num2){
cout << num1 + num2 << "\n"
}
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