Home > Net >  Conditional includes of header and implementation files containing functions with identical names
Conditional includes of header and implementation files containing functions with identical names

Time:10-17

When I try to compile the following 6 files all together, I get "multiple definition of `funcX(float, float)'" error.

If I remove "includeB.h" and "includeB.cpp" from the folder, then remaining 4 files are compiled. What am I doing wrong? Appreciate your help. Thanks in advance!

Assume my common.h file looks like this:

#ifndef COMMON_H
#define COMMON_H

// Uncomment needed Configuration Option
#define CONFIG  1 // Hardware Option 1
//#define CONFIG  2 // Hardware Option 2

#endif

and my main.cpp looks like this:

#include "common.h"

#if CONFIG == 1
  #include "includeA.h"
#else
  #include "includeB.h"
#endif

void main() {
  // put your main code here, to run repeatedly:
  float x;
  float a = 3.0;
  float b = 5.7;
  
  x = funcX(a, b);
}

My includeA.h file looks like this:

#ifndef INCLUDEA_H
#define INCLUDEA_H

float funcX(float a, float b);

#endif

and corresponding implementation file includeA.cpp:

#include "includeA.h"

float funcX(float a, float b) {
  return a * b;
}

My other header file includeB.h looks like:

#ifndef INCLUDEB_H
#define INCLUDEB_H

float funcX(float a, float b);

#endif

and corresponding to it the implementation file includeB.cpp:

#include "includeB.h"

float funcX(float a, float b) {
  return a   b;
}

CodePudding user response:

You can't have two definitions for the same function (funcX here). Two solutions:

  • set up your build system so that only one of includeA.cpp or includeB.cpp is linked to the executable.

  • add an #include "common.h" in includeA.cpp and includeB.cpp and compile only one version of funcX depending on the value of CONFIG.

In both case, I'd suggest considering having only one include.h which would contains declarations independent of CONFIG and include "common.h" and then includeA.h or includeB.h depending on CONFIG for the dependent part.

  • Related