Link to home
Start Free TrialLog in
Avatar of Troudeloup
Troudeloup

asked on

main.cpp functions to separate .cpp

I have written some utility functions in my own small project and now have too many functions to keep tidy, and also need to use them in other parts of the projects.

instead of copying them over and end up with a mess, is it possible to just do something like this?

#include "utility.functions.h"

I then compile with

g++ main.cpp util.cpp
ASKER CERTIFIED SOLUTION
Avatar of coanda
coanda

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
yes, you can, it is the usual practice.
Name of header file is not important, it could be "utility.functions.h", but usually is the same name as util.cpp (util.h)
Avatar of Troudeloup
Troudeloup

ASKER

#include "utility/functions.h"

that way I can use folders right?

that's cool.

what do I do with .h?
Or rather, what do I put inside .h?
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
i have only one .h and it was about a class..

can you post a working .h for this?

#include <iostream>

using namespace std;

int main()
{
    cout << "hello" << endl;
   
    return 0;

}
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Avatar of Infinity08
Infinity08
Flag of Belgium image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
And you can do the same if you just have some functions like :


/* ---- main.cpp ---- */
 
#include <iostream>
#include "util.h"
 
using namespace std;
 
int main() {
    someFun();                   // <--- we can call the functions here
    int a = someMoreFun(5);
    return 0;
}
 
 
/* ---- util.h ---- */
 
#ifndef UTIL_H                   // <--- add include guard to avoid including the header more than once
#define UTIL_H
 
void someFun();                  // <--- just the function prototypes here
int someMoreFun(int i);
 
// etc ...
 
#endif /* UTIL_H */
 
 
/* ---- util.cpp ---- */
 
#include "util.h"                // <--- include the header here !!
 
void someFun() {                 // <--- the function implementations go here
    // do something fun
}
 
int someMoreFun(int i) {
    // do something more fun
    return i;
}
 
// etc ...

Open in new window

coanda's (20847893), jaime_olivares's (20847991, 20848038), and mine (20848494) together answer the question.