Reputation: 2550
The following can be included from a .cpp file and the compiler won't complain about it.
typedef struct _SomeName {
char NameID[MaxSize];
UserId notUsed;
UserInstance instance;
bool operator==(const struct _SomeName& rhs) const
{
return (strncmp(NameID, rhs.NameID, MaxSize) == 0);
}
bool operator!=(const struct _SomeName& rhs) const { return !(*this == rhs); };
} SomeName;
How do I rewrite the above so that it's possible to include it from a .c file ?
Upvotes: 0
Views: 145
Reputation: 141544
The other solutions posted so far have a problem that you cannot use it in a project which mixes C and C++. I am guessing from the context of your question that you might want to do that. If you try that, you may get silent undefined behaviour because the structure could have a different layout in different translation units.
I'd suggest this version:
typedef struct
{
char NameID[MaxSize];
UserId notUsed;
UserInstance instance;
} SomeName;
#ifdef __cplusplus
inline bool operator==( SomeName const &lhs, SomeName const &rhs )
{
return strcmp(lhs.NameID, rhs.NameID) == 0;
}
inline bool operator!=( SomeName const &lhs, SomeName const &rhs )
{
return !operator==( lhs, rhs );
}
#endif
Upvotes: 1
Reputation: 207
You cannot get the exact functionality of the c++ struct, but if you use the __cplusplus
conditional, you can leave out the parts, the C compiler will not compile.
typedef struct _SomeName {
char NameID[MaxSize];
UserId notUsed;
UserInstance instance;
#ifdef __cplusplus
bool operator==(const struct _SomeName& rhs) const
{
return (strncmp(NameID, rhs.NameID, MaxSize) == 0);
}
bool operator!=(const struct _SomeName& rhs) const { return !(*this == rhs); };
#endif
} SomeName;
If you need the equal and not equal operator, in both c and c++, I suggest you remove the operator definitions from the struct, and write a pure c interface implementing a SomeNameEquals
and SomeNameNotEquals
function.
Upvotes: 1
Reputation: 180058
Supposing that declarations of types UserId
and UserInstance
are in scope, you should be able to write this:
typedef struct _SomeName {
char NameID[MaxSize];
UserId notUsed;
UserInstance instance;
#ifdef __cplusplus
bool operator==(const struct _SomeName& rhs) const
{
return (strncmp(NameID, rhs.NameID, MaxSize) == 0);
}
bool operator!=(const struct _SomeName& rhs) const { return !(*this == rhs); };
#endif
} SomeName;
Upvotes: 1