Home > Blockchain >  how to avoid multiple definitions when making copies of header files
how to avoid multiple definitions when making copies of header files

Time:09-16

I came across this problem and was trying to figure out the best solution.

I am currently working on a library called lib1.h and making some changes to it. I don't want to modify the original file directly so I made a copy and named it lib2.h.

All declaration and definitions are coded in lib1.h and lib2.h, lib1.c and lib2.c, respectively. The code looks like this:

/* lib1.h */
#ifndef LIB1_H
#define LIB1_H

int method1();
int method2();
...

#endif
/* lib2.h */
#ifndef LIB2_H
#define LIB2_H

int method1();
int method2();
...

#endif
/* lib1.c */
#include "lib1.h"

int method1()
{
 // old implementation 
};
int method2()
{
 // old implementation 
};
...
/* lib2.c */
#include "lib2.h"

int method1()
{
 // new implementation 
};
int method2()
{
 // new implementation 
};
...

Since I am not changing the names of all functions, I am getting multiple definition errors. My current solution is to move the original library out of the current directory and do a make clean and then compile. While this solution works for me, I am just curious if there is any way to keep the two header files in the same directory, or what is a better workflow.

I'd appreciate any pointers.

CodePudding user response:

Multiple definitions is a linker error, not compilation error. Why do you link both libraries? I guess you need only the newer (fixed) one. There are a few solutions:

  1. Delete the old code,
  2. Put #ifdef 0 on the old code, or move it to separate directory
  3. Use -DNEW_CODE flag in make file and use #ifndef NEW_CODE in old library and #ifdef NEW_CODE in new library. You can quickly switch between versions by editing compilation flags
  4. Just dont include the older version in your make file. Even if you compile it, dont link it.
  5. If you need both versions of library (to compare results?) use prefix to functions or compile as C and wrap the functions in name spaces
  6. Use macro hacks to automatically add prefix or suffix to function names. Really dont recommend this approach.
  7. Use source control, like git, and change the library in place, and maintain only 1 copy. you can always revert your commits to get the previos version
  •  Tags:  
  • c
  • Related