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

南笙酒味 提交于 2019-12-04 06:57:14

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.

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.

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.

#include "calc.cpp"

Don't do that - it includes the function definition in any translation unit that includes the header, so you'll end up with multiple definitions.

Without that, your code should be fine if you build a program from both source files. main.cpp will include a declaration, so that it knows that function exists; the definition from the other source file will be included in the program by the linker.

This is pretty simple. Do not Include your "calc.cpp" file in "MyHeader.h" file.

Take also a look at C/C++ IncludeGuard here

This is a fundamental of C/C++ programming. You will need to use it many times.

Protect your "myHeader.h"

#ifndef ADD_HEADER
#define ADD_HEADER
 int add(int, int);
#endif // ADD_HEADER

Do not include calc.cpp . This is causing the redefinition

you can include myHeader.h in calc.cpp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!