Public Group

# combining files

This topic is 4908 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

i don't know very much about combining cpp files and h files with your project, so i need a little help. im pretty sure you'd use .cpp for functions, but how would you go about doing that. every time i try it, it says there is an error, and it can't find the function.

##### Share on other sites
use a function prototype:

[function.cpp]

#include "function.h"

//Here the function itself

int funtion(void)
{
return(0);
}
//your finshed with the function and this file so
//save and on to creating the other files

[function.h]
//it is always good to do :
#ifndef _FUNCTION_H
#define _FUNCTION_H
//include what u need here

int function(void); // this is a prototype for a function

//finished here just save and creat cpp file with a main function
#endif //close the if statements
[main.cpp]

//include what u need here
#include <function.h>

void main()
{
int my_number;
my_number = function();
}

// it should be that simple

##### Share on other sites
First make sure all your files, .cpp and .h are properly added to your project (assuming you are using an IDE, like VC++ or DevC++, otherwise you have to meake sure to compile all files when running the compiler).

The main principle is that .h files contain declarations while .cpp files contain definitions. If you have a function foo() which you want to call from main(), but you don't want to have lying around in the same .cpp file as main(), then you can create a file foo.h and put in the following declaration:
#ifndef FOO_H#define FOO_Hvoid foo(void);#endif

Then you create a file foo.cpp in which you put the definition of the function, for example the following code:
#include "foo.h"void foo(void){  // Things that foo() should do...  // ...  // ...}

In your main .cpp file you put the line
#include "foo.h"

to be able to call foo().

That's about it. Often it is convenient to let extra .cpp and .h files come in pairs with the same name. Also it is worth noting that if foo() uses something from another library, iostream for example, you should put the #include for that in foo.h, not in foo.cpp. This way the #ifndef clause will prevent multiple includes of the same file/library and the compiler will be happy.

Good luck.

1. 1
2. 2
JoeJ
20
3. 3
frob
20
4. 4
5. 5

• 10
• 11
• 12
• 13
• 9
• ### Forum Statistics

• Total Topics
632210
• Total Posts
3004792

×