C Project - two libraries use the same typedef for different types

I am working on a project using the MODBUS2 library, and I want to add FatFs lib to it to interact with the SD card. Both libraries use the SHORT identifier for SHORT and int respectively, and the compiler throws this error:

 #258 invalid redeclaration of type name "SHORT" 

How can I get around this?

+5
source share
3 answers

You need to restructure your project so that no translation unit of your library should include headers from both libraries (the translation unit is a fancy name for the C file).

One approach is to write your own subtle wrapper functions around MODBUS2 and FatFs. Each shell should include headers for the library that it wraps, so there would be no compile-time collision. Then the main module of your library will be programmed to your "wrappers", not including the MODBUS2 or FatFs headers.

+7
source

Suppose library 1 has

 typedef int SHORT; 

and library 2 has

 typedef short SHORT; 

Suppose you have this code:

 #include "lib1.h" #include "lib2.h" 

You may be able to fix the compilation error as follows:

 #define SHORT LIB1_SHORT #include "lib1.h" #undef SHORT #define SHORT LIB2_SHORT #include "lib2.h" #undef SHORT 

If you do this, you must do it sequentially for all #include directives in your code. If you have too many #include s, this is not too tiring.

If you donโ€™t want to keep these rules in mind, add #define and #undef as the first and last thing in all the problematic library headers.

+3
source

Libraries that use these SHORT typedef without a prefix are poorly designed since there are no namespaces in C, so they severely restrict users. Good, but we have to live with it.

If typedefs defined the same type, there would be no problem as you can repeat:

 typedef int SHORT; typedef int SHORT; 

as many times as you want if it defines the same base type. But there are different types, so the problem.

One hack will use the word-only replacement throughout the FatFs library, including / sources, to replace SHORT with FF_SHORT .

Now you can enable both libraries without any conflicts.

  • main advantage: no need for additional changes or wrappers (for example, offers the best answer): fast and dirty.
  • main disadvantage: it must be executed every time the library interface is updated.
+1
source

Source: https://habr.com/ru/post/1274770/


All Articles