Question: I have two class implementations (`.cpp files`)

They both need a function which was implemented in a `header`(.h) file. Both the .cpp files include the .h file. After compilation, the two `.cpp` files become two `.o` files.

Do the function be defined twice when linking the two object files? 

Can `#ifndef` prevent this situation?

I used `#ifndef` but I got the following message,

```
ld: 1 duplicate symbol for architecture x86_64

```

Answer: 
You must understand the difference between a function *declaration* (a statement that a function with a given name and signature exists) and a function *definition* (the code that determines what the function actually does).

If you *define* the function in the header, then the function will be defined in each object file, and you will get a conflict when you try to link them together; `#ifndef` will not solve this problem.

There will be no such problem if you *declare* the function in the header, and *define* it in a source file (which must be compiled into an object, and linked with the objects that use it). In this simple case, `#ifndef` is not needed.

For example, the function `foo` can be declared in `foo.h`:

```
int foo(int);

```

and defined in `foo.cpp`:

```
int foo(int n)
{
  return(n+3);
}

```

The `#ifndef` macro solves a different problem.
As an alternative to Beta's answer, you can *define* a free function inside a header file which will be included in multiple translation units, by using the `inline` keyword. Consider this:

```
// Foo.h

int foo(){return 1;}

// UsesFoo1.cpp

#include "Foo.h"
int usesFoo2(){return foo();}

// UsesFoo2.cpp

#include "Foo.h"
int usesFoo1(){return foo();}

// Main.cpp

#include <iostream>
int usesFoo1();
int usesFoo2();

int main()
{
   std::cout << usesFoo1() + usesFoo2() << std::endl;
}

```

This produces a linker error because `int foo()` is defined in two separate translation units. However, no error is generated if you add the `inline` keyword here:

```
// Foo.h

inline int foo(){return 1;}

```

Note: functions defined inside class definitions are implicitly have the `inline` keyword, so you can omit it there.