Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function already defined error in C++

I have a file called "SimpleFunctions.h" defined as follow:

#ifndef SIMPLEFUNCTIONS_H
#define SIMPLEFUNCTIONS_H

namespace my_namespace {

double round(double r) { return (r > 0.0) ? floor(r + 0.5) : ceil(r - 0.5); }
float round(float r) { return round((double)r); }

}

#endif // SIMPLEFUNCTIONS_H

This file was previously included in only one file and it was working fine.

Now today I have included it in a second file and it no longer works. At link time, it tells me that the function is already defined in "firstfile.obj".

However, since I am using include guards, I would expect the functions to be defined only once, or am I missing something?

like image 605
laurent Avatar asked Aug 06 '11 04:08

laurent


People also ask

How to resolve error LNK2005?

To fix this issue, recompile all files that include the packaged function. This error can occur if the symbol is defined differently in two member objects in different libraries, and both member objects are used.

Can we define function after Main?

If you define function after main() then you must provides it's prototype before main() first, ( so then after main , you can provide defination ).


1 Answers

By default, these functions have external linkage. That means each translation unit has functions called double round(double r) and float round(float r), which causes a name collision at link time.

Some possible solutions are:

  1. Declare the functions as static, which implies internal linkage
  2. Inline the functions
  3. Move the implementation out of the header and into a c/c++ file

Read more here: What is external linkage and internal linkage?

By the way, include guards protect a single translation unit from including a header file multiple times. That's a different issue that what you're seeing here.

like image 133
pepsi Avatar answered Oct 05 '22 12:10

pepsi