Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

constants in header file cause multiple definition errors

FCORE macro is for shared library exporting.

This is my header file FMath.h

namespace FMath {
    // ...
    FCORE const float PI_32 = 3.14159265359f; // pi
    FCORE inline float  Floor(float value) { return floorf(value); }
namespace FConvert {
    // ...
    FCORE const float DEG_TO_RAD_32 = 0.01745329252f; // pi / 180
    FCORE inline float ToRadian(float degree) { return degree * DEG_TO_RAD_32; }
}
}

All of the constant values in my FConvert namespace cause error but not for declared in FMath. I didn't understand why?

FMeshTraits.obj:-1: error: LNK2005: DEG_TO_RAD_32 already defined in FMesh.obj

Edit: I'm sorry I didn't say that I've already used this macro.

#ifndef FMATH_H
#define FMATH_H

// All of the code is here

#endif
like image 497
Cahit Burak Küçüksütcü Avatar asked Dec 06 '25 02:12

Cahit Burak Küçüksütcü


1 Answers

It looks like you have two .cpp files FMeshTraits.cpp and FMesh.cpp (two separate 'translation units' in the jargon). Each of these is compiled into a separate .obj file.

The next step is to link together these .obj files into a single executable. But - if there are multiple conflicting definitions for a symbol, then the linker will fail with the error message you see.

The usual way to avoid this is to only have declarations in the header file (i.e. declaring types but no definitions), and put all definitions into the .cpp files. That way, you never have the same definition in more than one .obj file, so you don't get linker conflicts.

So, in FMath.h you would have :

FCORE const float DEG_TO_RAD_32;

and in FMath.cpp you would have :

DEG_TO_RAD_32 = 0.01745329252f;
like image 86
Graham Griffiths Avatar answered Dec 08 '25 16:12

Graham Griffiths



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!