cancel
Showing results for 
Search instead for 
Did you mean: 

how to include C code in C++ and the opposite?

KFrey.1
Associate II

I have a problem that I cannot include C code in C++ and the opposite. Different sites suggest to solve this problem by including the header file of C in the header file of C++ (Model.hpp) like:

#ifdef __cplusplus

extern "C"{

#endif

#include "coreTransferBufferAPI.h"

#ifdef __cplusplus

      }

#endif

In the code file Model.cpp, I try to use a function called (CB_Display_GetValues(&values) from this header.

CB_DisplayValues_t is also defined in this header, but doesn't show any errors.

float Model::getTempValue()

{

      CB_DisplayValues_t values;

      if(CB_Display_GetValues(&values)==REPORT_OK)

      {

            return values.cellTemperature;

      }

      return NULL;

}

The call of the function (CB_Display_GetValues(&values)) gives an undefined reference error:

/../TouchGFX/gui/src/model/Model.cpp:32: undefined reference to `CB_Display_GetValues'

Do you have a solution for this problem or do you know how to solve it? How would including a C++ code in C work (opposite way)?

Thank you very much and a festive holiday, K.Frey1

1 ACCEPTED SOLUTION

Accepted Solutions
TDK
Guru

Calling C code from C++ is easy. Ensure the function is declared prior to calling it (typically by including the appropriate header) and just call the function. Perhaps there is a typo or other mistake which is preventing this from working in your case.

Calling C++ code from C is more complicated. You need to ensure the functions have C linkage by enclosing them in extern "C" braces, and then you just call them.

If you feel a post has answered your question, please click "Accept as Solution".

View solution in original post

4 REPLIES 4
TDK
Guru

Calling C code from C++ is easy. Ensure the function is declared prior to calling it (typically by including the appropriate header) and just call the function. Perhaps there is a typo or other mistake which is preventing this from working in your case.

Calling C++ code from C is more complicated. You need to ensure the functions have C linkage by enclosing them in extern "C" braces, and then you just call them.

If you feel a post has answered your question, please click "Accept as Solution".
KFrey.1
Associate II

Dear TDK, thank you for your reply.

As you can see, I did declare the c-type header-file prior to calling it and then called the function. I don't think it's a typo because I checked it several times and you can see the code above. What other mistake could it possibly be?

TDK
Guru

Where is CB_Display_GetValues defined (C or CPP file name, not header)? Is that file getting compiled? Examine the console log and show proof.

If you feel a post has answered your question, please click "Accept as Solution".
KFrey.1
Associate II

TDK, you were right "CB_Display_GetValues" a function in the c-headerfile was not properly declared. Thank you, and sorry for your trouble