Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define function in other source file:C++ CodeBlocks

I am trying to separate my functions in another source file. But i am getting error that multiple definition on add function.

Main source file

Main.cpp

#include<iostream>
#include "myHeader.h"
using namespace std;

int main()
{
int result = add(1,2);
}

Header file "myHeader.h"

#include "calc.cpp"
int add(int, int);

Other Source file "calc.cpp"

int add(int a, int b)
{
return a+b;
}
like image 475
CODError Avatar asked Jan 16 '14 16:01

CODError


3 Answers

Don't include calc.cpp from myHeader.h. Except for that one line, your example is right as far as headers go. (main() should return a value).

calc.cpp and main.cpp are two different "compilation units" which will be compiled separately into object files. The two object files are then combined into one executable by a linker.

like image 149
TypeIA Avatar answered Nov 01 '22 14:11

TypeIA


What you need is:

"myHeader.h"

#ifndef MY_HEADER
#define MY_HEADER
 int add(int, int);
#endif 

calc.cpp

#include "myHeader.h"

int add(int a, int b)
{
 return a+b;
}

main.cpp

#include "myHeader.h"

int main()
{
  int result = add(1,2);
  return 0;
}

You don't include the .cpp into the .h . The header file is used to tell the compiler the existence of a function with the specified prototype, but the liker will be tke care of matching up the call to a function with the implementation of that function.

Also, it's usually a good idea to give you header file and .cpp the same name, so calc.h and calc.cpp rather than myHeader.h.

like image 39
Sean Avatar answered Nov 01 '22 15:11

Sean


You problem is that you include a Code File (cpp) into a header. You should do the inverse. Include your header "myHeader.h" into calc.cpp. And to be coherent, you should name your header the same name as your Code file, so calc.h for the header and calc.cpp for you code.

like image 1
jordsti Avatar answered Nov 01 '22 13:11

jordsti