Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ program using a C library headers is recognizing "this" as a keyword. Extern "C" error?

My C++ program needs to use an external C library. Therefore, I'm using the

extern "C"
{
   #include <library_header.h>
}

syntax for every module I need to use.

It worked fine until now. A module is using the this name for some variables in one of its header file. The C library itself is compiling fine because, from what I know, this has never been a keyword in C.

But despite my usage of the extern "C" syntax, I'm getting errors from my C++ program when I include that header file.

If I rename every this in that C library header file with something like _this, everything seems to work fine.

The question is:

Shouldn't the extern "C" syntax be enough for backward compatibility, at least at syntax level, for an header file? Is this an issue with the compiler?

like image 378
nyarlathotep108 Avatar asked Sep 03 '14 14:09

nyarlathotep108


People also ask

What is extern C in header file?

Extern is a keyword in C programming language which is used to declare a global variable that is a variable without any memory assigned to it. It is used to declare variables and functions in header files. Extern can be used access variables across C files.

Which keyword will cause a program to access an external library in C ++?

extern. The extern keyword declares that a variable or a function has external linkage outside of the file it is declared.

Why does C use headers?

The header file eliminates the labor of finding and changing all the copies as well as the risk that a failure to find one copy will result in inconsistencies within a program. In C, the usual convention is to give header files names that end with .

Can you #include in a header file C?

C language has numerous libraries that include predefined functions to make programming easier. In C language, header files contain the set of predefined standard library functions. You request to use a header file in your program by including it with the C preprocessing directive “#include”.


1 Answers

Shouldn't the extern "C" syntax be enough for backward compatibility, at least at syntax level, for an header file? Is this an issue with the compiler?

No. Extern "C" is for linking - specifically the policy used for generated symbol names ("name mangling") and the calling convention (what assembly will be generated to call an API and stack parameter values) - not compilation.

The problem you have is not limited to the this keyword. In our current code base, we are porting some code to C++ and we have constructs like these:

struct Something {
    char *value;
    char class[20]; // <-- bad bad code!
};

This works fine in C code, but (like you) we are forced to rename to be able to compile as C++.

like image 108
utnapistim Avatar answered Sep 18 '22 09:09

utnapistim