dimanche 27 juin 2021

multiple definition of `var'; obj/Class.o:(.bss+0x0): first defined here

I have a GlobalVars.h file in which I declare some variables (mutexes, condition_variables, ints...) that I want to use from other cpp files. In those cpp files, I include that GlobalVars.h with include guards, and when I compile the whole project, it gives me the next error:

g++ -o exec/Manager obj/Manager.o -pthread -std=c++11 obj/PaySystem.o obj/SSOOIIGLE.o 
/usr/bin/ld: obj/PaySystem.o:(.bss+0x40): multiple definition of `semMutexPay'; obj/Manager.o:(.bss+0x0): first defined here
/usr/bin/ld: obj/PaySystem.o:(.bss+0x80): multiple definition of `waitPayFinish'; obj/Manager.o:(.bss+0x40): first defined here
/usr/bin/ld: obj/PaySystem.o:(.bss+0x210): multiple definition of `counter'; obj/Manager.o:(.bss+0x1d0): first defined here
...

My files: GlobalVars.h:

std::mutex semMutexPay;
std::mutex waitPayFinish;
int counter;

PaySystem.cpp:

#ifndef __VARS_H__
#define __VARS_H__
#include "GlobalVars.h"
#endif

void PaySystem::operator()() {
  while(true) {
    std::unique_lock<std::mutex> ulPayQueue(semMutexPay);
    if (counter > 5)
      doOtherStuff();
  }
}

Manager.cpp:

#ifndef __VARS_H__
#define __VARS_H__
#include "GlobalVars.h"
#endif
#ifndef __PAY_SYSTEM_H__
#define __PAY_SYSTEM_H__
#include "SistemaPago.h"
#endif

int main(int argc, char *argv[]) {
  PaySystem ps;
  std::thread paySystemThread(ps);
  doSomeStuff();
}

void someMethod() {
  counter++;
}

My makefile:

DIROBJ := obj/
DIREXE := exec/
DIRHEA := include/
DIRSRC := src/

CFLAGS := -I $(DIRHEA) -c -Wall -ansi
LDLIBS := -pthread -std=c++11
CC := g++

all: dirs PaySystem Manager 

dirs:
    mkdir -p $(DIROBJ) $(DIREXE)

Manager: $(DIROBJ)Manager.o
    $(CC) -o $(DIREXE)$@ $^ $(LDLIBS) $(DIROBJ)PaySystem.o

PaySystem: $(DIROBJ)SistemaPago.o

$(DIROBJ)%.o: $(DIRSRC)%.cpp
    $(CC) $(CFLAGS) $^ -o $@ $(LDLIBS)

clean: 
    rm -rf *~ core $(DIROBJ) $(DIREXE) $(DIRHEA)*~ $(DIRSRC)*~

I tried doing the include guard in other ways but none works.

Aucun commentaire:

Enregistrer un commentaire