c++linker-errorsraylib

How to fix the error: multiple definition of 'GuiEnable'?


I am having some trouble configuring raygui.h with cmake using two targets, a library and a executable. There is a repository here with the exact files that causes errors of multiple definition of SomeFunction during the build. The errors are like below:

/usr/bin/ld: libgame-lib.a(hello_world.cpp.o): in function `GuiEnable':
hello_world.cpp:(.text+0x0): multiple definition of `GuiEnable'; CMakeFiles/exe.dir/src/main.cpp.o:main.cpp:(.text+0x0): first defined here

It's like raygui.h declarations were all made twice.

The problem does not occur in the master branch, where only one target is linked directly with raygui.h.

These are the files in the branch that has the problem:

hello_world.hpp

#include "raylib.h"
    
#define RAYGUI_IMPLEMENTATION
#include "raygui.h"

void hello_world();

hello_world.cpp

#include "hello_world.hpp"

void hello_world() {
  InitWindow(300, 300, "Hello World with raylib.");

  while (!WindowShouldClose()) {
    BeginDrawing();
    ClearBackground(BLACK);    
    DrawText("Hello World", 120, 150, 12, RED);    
    GuiButton((Rectangle) {115, 180, 80, 16}, "Hello World");    
    EndDrawing();    
  }
}

main.cpp

#include "hello_world.hpp"

int main() {
  hello_world();  
  return 0;
}

Solution

  • This should be in a single .cpp file:

    #define RAYGUI_IMPLEMENTATION
    #include "raygui.h"
    

    #define RAYGUI_IMPLEMENTATION should be removed from hello_world.hpp.

    When you placed it in the header file, #include "hello_world.hpp" was used in several compilation units, you got multiple definitions.

    https://github.com/raysan5/raygui/blob/master/README.md

    NOTE: raygui is a single-file header-only library (despite its internal dependency on raylib), so, functions definition AND implementation reside in the same file raygui.h, when including raygui.h in a module, RAYGUI_IMPLEMENTATION must be previously defined to include the implementation part of raygui.h BUT only in one compilation unit, other modules could also include raygui.h but RAYGUI_IMPLEMENTATION must not be defined again.