Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where do you typically declare and define functions outside a class in c++?

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?

like image 646
Jason Avatar asked Sep 14 '25 14:09

Jason


2 Answers

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;
}
like image 140
Edward Karak Avatar answered Sep 17 '25 06:09

Edward Karak


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"

}
like image 44
edgar_is Avatar answered Sep 17 '25 05:09

edgar_is