Vineet
Vineet

Reputation: 317

C enum using in c++ file

mode.h :: from c

typedef enum Mode_t
{
    MODE_READ       = 0,
    MODE_WRITE      = 1,
    MODE_READ_WRITE = 2
}Mode_T;
int callfunc(int, Mode_T);

mode.cpp

#include "mode.h"
extern "C" int callfunc(int, Mode_T);

int run()
{
   callfunc(2, MODE_WRITE);
}

I get the following compilation error:

Mode_T has not been declared.

I tried using extern for the enum as well but then it gave the following error :

Error: use of enum 'Mode_t' without previous declaration

How to use C enums in C++ file ?

Upvotes: 1

Views: 501

Answers (1)

eerorika
eerorika

Reputation: 238351

How to use C enums in C++ file ?

Just like all C declarations, you must use extern "C".

You can put it around the include directive for example:

extern "C" {
    #include "mode.h"
}

A common pattern is to use

#ifdef __cplusplus
extern "C" {
#endif

#ifdef __cplusplus
}
#endif

at the beginning and the end of a header file itself in order to make the header usable in both languages without having to know what language that header uses.

Upvotes: 4

Related Questions