[C++] Multple c++ files causes "multiple definition" error?

I'm using multiple C++ files in one project for the first time. Both have need to include a protected (#ifndef) header file. However, when I do that, I get a multiple definition error.

From what I found from research, adding the word inline before the function fixes the error. Is this the right way to do this, and why does it work? Should I make a habbit of just declaring any function that might be used in two .cpp files as inline?

Thanks.
Unless the function is actually small enough that you would want to inline it, you should just define it in a single source file (usually named the same as the relevant header) and include only the prototype in the header.
That's what I discovered as I did more research.

So what I have is two one .cpp file that calls the header directly, and one indirectly (Another include includes it) and then two other header files that include it.

So what do I need to do to get rid of the error?
if you do this in ALL your header files, you will never have any problem regardless if you include multiple times your header

1
2
3
4
5
6
7
//file filename.h
#ifndef FILENAME_H
#define FILENANE_H

// code

#endif 


every header must define a "prevent" marcro that forbids any include action if the macro is still defined for that module (so, preventing multiple declarations). Every macro in every header should be unique.... usually I call my macro with the filename.... with the syntax shown in the example I posted
I know this has been marked as "solved", but just to be clear:

- you put the actual definition of the function, i.e. the code for what the function actually does, in a single source file (.cpp)

- you put the declaration of the function in a header file (.h)

- any file that contains code which calls that function needs to include the header file

- when compiling the application, the linker should link the object files created from all the source files together, including the one that contains the definition of the function.

Hope that's clear!
Topic archived. No new replies allowed.