greenpiece
greenpiece

Reputation: 641

Build C project to call functions from C++ library in the same solution in Visual Studio

Is it possible in Visual Studio to have one project with C++-library and the other one written in C in the same solution, and to call functions from this library using C?

What I have in library header:

#ifdef __cplusplus
  #define EXTERN extern "C"
#else
  #define EXTERN
#endif

#ifndef LIB_API
  #ifndef LIB_STATIC
    #ifdef LIB_EXPORT
      #define LIB_API EXTERN __declspec(dllexport)
    #else
      #define LIB_API EXTERN __declspec(dllimport)
    #endif
  #else
    #define LIB_API
  #endif
#endif

LIB_API uint32_t Func(int8_t *arg);

I want to link statically to this library from my C-project, so I choose dependency from the library project, define the macro LIB_STATIC in preprocessor definitions, choose "Compile as C Code (/TC)" option and call this function. What I get is linker error

error LNK2019: unresolved external symbol _Func referenced in function _main

When I look at lib file I can find there something like Func and not _Func. What an I doing wrong?

(Forgot to add, there's appropriate implementation of function in a .cpp module of library)

Answer from Angew and AnatolyS

We need to define LIB_API to EXTERN in static library case so the right preprocessor block will be:

#ifndef LIB_API
  #ifndef LIB_STATIC
    #ifdef LIB_EXPORT
      #define LIB_API EXTERN __declspec(dllexport)
    #else
      #define LIB_API EXTERN __declspec(dllimport)
    #endif
  #else
    #define LIB_API EXTERN
  #endif
#endif

Upvotes: 0

Views: 1070

Answers (1)

AnatolyS
AnatolyS

Reputation: 4319

To use C++ function from C code you have to export such function as C, so change your definition of LIB_API for static linking:

#else
 #define LIB_API EXTERN
#endif

Upvotes: 1

Related Questions