+ 1
Can we use functions in seperate files?
I wanted to do like this:I write some functions and save it "something.h".After that when I want to make other programs I will copy that .h file to my program's folder,and I will include that(#include "something.h").And I want to call my written function.How can I do it?
3 Answers
+ 3
Header files should actually only used for forward declarations of classes and functions.
Use the .cpp-files to put your function-definition in.
for example:
the Header-File myfunctions.h:
//Header-Guards
#ifndef MYFUNCTIONS_H
#define MYFUNCTIONS_H
//declare function add
int add (int a, int b);
#endif
The Source-File myfunctions. cpp:
#include "myfunctions.h"
int add (int a, int b)
{
return a+b;
}
The main.cpp file:
#include <iostream>
#include "myfunctions. h"
int main ()
{
std::cout << add (3,5)<< std::endln;
return 0;
}
Everywhere where you wanted to use the function add, you would have to put both files header and src file of the function in the same Directory.
If this is not enough you could inform yourself about code-librarys.
+ 2
you already described your way, how to reuse a header file. this would look like:
sharedfunctions.h
namespace Shared
{
void func() { }
}
Main.cpp
#include "sharedfunctions. h"
// or "D:/Dev/Lib/sharedfunctions.h"
int main()
{
Shared::func();
return 0;
}
i would recommend you to create a Lib/DLL of your Code which You want to Reuse.
0
Oh yess!It worked!!!!Thanks a lot!