c and c++ mixed - c++

I need to call cpp method from c file.
I have written this interface for that..
cpp file
extern "C" void C_Test(int p){
Class::CPP_Test(p);
}
c file
extern void C_Test(int p);
void C_Function(){
C_Test(10); //error
}
I get error in c file "undefined reference to C_Test(int)"
any idea whats wrong?

You must declare extern only for function prototype, and ensure to link correctly. In addiction to this, CPP_Test(p) must be a static member of Class, otherwise your code does not work. At last, extern "C" must enclose in brackets its content, more like
extern "C"
{
void C_Test(int p)
{
Class::CPP_Test(p);
}
}
Tell us if this works.

Are you compiling both with a C++ compiler? C++ compilers may compile a C-source file as C++, in which case it will perform name mangling, so you need to be sure to compile the C source file with a C compiler.

I am using C++ compiler for both types of files.
Without "C" it works!! Also without extern "c" it works!

Related

how does extern "C" allow C++ code in a C file?

In order to use C++ code in a C file, I read that we can just do extern "C" { (where the c++ code goes here)}, but when I try printing something out using cout, I keep getting an error because it does not recognize the library . I think I am just confused on how extern "C" allows you to use C++ code in C.
The opposite is true. You can use extern C to add code you want to compile as C code using a C++ compiler.
Unless I'm missing something you can't compile C++ code with a C compiler.
The extern "C" construct is a C++-specific syntax, no C compiler will understand it.
That's why you will almost always see it paired with some conditional compilation like
#ifdef __cplusplus
extern "C" {
#endif
...
#ifdef __cplusplus
}
#endif
What extern "C" does is simply to inhibit name mangling meaning that symbols defined in a C++ source file can be used in a C program.
This allows you to have a project with mixed C and C++ sources, and the C source can call the C++ functions that have been defined as extern "C".
Very simple, and stupid, example just to show the point:
Lets say we have a C source file, compiled with a C compiler:
#include <stdio.h>
void foo(void); // Declare function prototype, so it can be called
int main(void)
{
printf("Calling foo...\n");
foo();
printf("Done\n");
return 0;
}
Then we have a C++ source file for the foo function:
#include <iostream>
extern "C" void foo()
{
std::cout << "Hello from foo\n";
}
The C source file is compiled with a C compiler, and the C++ source file is compiled with a C++ compiler. Then the two object files are linked together to form the executable program. Because foo was defined as extern "C" it's symbol name in the object file is not mangled, and the linker can resolve the reference from the object file created by the C compiler.
It works in the other direction as well. Because symbols in C are not mangled the C++ compiler needs to know that, and that is done by declaring the C symbols extern "C", usually in a header file using the conditional compilation as shown above. If extern "C" was not used, the C++ compiler would think that the symbols were C++ symbols, and mangle the names leading to linker problems when the linker can't find the mangled symbols.
Equally stupid example: First a C++ source file
#include <iostream>
extern "C" void bar(); // Declare function prototype as an unmangled symbol
int main()
{
std::cout << "Calling bar...\n";
bar();
}
Then the C source file
#include <stdio.h>
void bar(void)
{
printf("Inside bar\n");
}
extern "C" is a way of putting C code in C++ code. More specifically it tells the compiler to disable certain things like function overloading so that it can also turn off the name mangling. In C++ a simple function like:
int add(int a, int b) {
return a+b;
}
Will actually get some funky name in the library to denote the parameters so that if you define another function like:
double add(double a, double b) {
return a+b;
}
That it knows which one to call. You don't want that if you're trying to use a C library and that's what extern "C" is for. All of this being said, extern "C" does not allow C++ in a C program.
Exported C++ symbols, as generated my the compiler, are mangled to include additional type information about the symbol to the linker.
So the following overloaded functions would be distinguishable by the linker in C++, but not C:
int fn();
int fn(int);
int fn(char*);
int fn(char*) const;
int fn(const char*);
The extern "C" { ... } syntax allows symbols (or references to C symbols) to be defined in C++ code without using the mangling rules.
This allows such C++ code to be linked with C libraries.

How to call a C++ function from C code

I have a C++ class with its header CFileMapping.cpp and CFileMapping.h I want to call the c++ function CFileMapping::getInstance().writeMemory( ) in my C code.
Even when I wrapped my C++ code and added
#ifdef __cplusplus
extern "C"
in the header file to deal with the c++ code and added
extern "C"
in the cpp file, I still can't call my function like this
CFileMapping::getInstance().writeMemory().
Could any one help me? I want to keep my c++ code and be able to call it when I want.
You should create C wrapper for your C++ call:
extern "C"
{
void WriteMemFile()
{
CFileMapping::getInstance().writeMemory( );
}
}
// The C interface
void WriteMemFile();
IMPORTANT: The extern "C" specifies that the function uses the C naming conventions.

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?
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++.
Strangely enough, many compilers don't forcibly disallow keyword redefinition through the preprocessor:
#include <iostream>
// temporary redefinition to compile code abusing the "this" keyword
#define cppThis this
#define this thisFunction
int this() {
return 1020;
}
int that() {
return this();
}
// put the C++ definition back so you can use it
#undef this
#define this cppThis
struct DumpThat {
int dump() {
std::cout << that();
}
DumpThat() {
this->dump();
}
};
int main ()
{
DumpThat dt;
}
So if you're up against a wall, that could let you compile a file written to C assumptions that you cannot change.
It will not--however--allow you to get a linker name of "this". There might be linkers that let you do some kind of remapping of names to help avoid collisions. A side-effect of that might be they allow you to say thisFunction -> this, and not have a problem with the right hand side of the mapping being a keyword.
In any case...the better answer if you can change it is...change it!
If extern "C" allowed you to use C++ keywords as symbols, the compiler would have to resolve them somehow outside of the extern "C" sections. For example:
extern "C" {
int * this; //global variable
typedef int class;
}
int MyClass::MyFunction() { return *this; } //what does this mean?
//MyClass could have a cast operator
class MyOtherClass; //forward declaration or a typedef'ed int?
Could you be more explicit about "using the this name for some variables in one of its header files"?
Is it really a variable or is it a parameter in a function prototype?
If it is the latter, you don't have a real problem because C (and C++) prototypes identify parameters by position (and type) and the names are optional. You could have a different version of the prototype, eg:
#ifdef __cplusplus
extern "C" {
void aFunc(int);
}
#else
void aFunc(int this);
#endif
Remember there is nothing magic about header files - they just provide code which is lexically included in at the point of #include - as if you copied and pasted them in.
So you can have your own copy of a library header which does tricks like the above, just becoming a maintenance issue to ensure you track what happens in the original header. If this was likely to become an issue, add a script as a build step which runs a diff against the original and ensures the only point of difference is your workaround code.

__cplusplus macro to tell g++ about C header declarations not working strangely

I have a mix of C C++ code. All compiled with g++. Wherever I have C headers I have the contents of the header file included inside
#if defined(__cplusplus)
extern "C" {
#endif
and
#if defined(__cplusplus)
extern "C" {
#endif
But in one C header file I get g++ compilation errors where I have accidentally used a parameter name as template , which obviously is incorrect and in conflict with c++ keyword template.
I know I can go and change this parameter name, but I am thinking why is this extern "C" declaration not working and why is the header file considered as C++ code and not C as I intended to.
g++ version 4.1.1 Linux Red Hat Enterprise.
The extern "C" only tells the compiler (actually, the linker) that C++ name mangling doesn't apply to the functions declared in that scope. It has nothing to do with the syntax or keywords themselves.
Your best solution is to rename the conflicting symbols.
Consider:
extern "C" {
namespace n
{
int& foo(bool b)
{
if (!b)
throw std::invalid_argument("fail!");
static int i = 0;
return ++i;
}
}
}
This function has C language linkage, but uses references, namespaces and exceptions, which I hope demonstrates that extern "C" doesn't magically switch the compiler to compiling C, it just tells the compiler to use C calling conventions and symbol-naming conventions for the functions and variables with C language linkage (which usually just means it disables name-mangling and causes matching declarations in different namespaces to refer to the same entity.)

Impact of using extern "C" { on C++ code when using g++

When using G++ (e.g. version 4.5 on Linux) can anyone explain what will/can happen if a user writes a header file for a mixed C/C++ system like this:
#ifdef __cplusplus
extern "C" {
int myCPPfunc(some_arg_list....); /* a C++ function */
}
#endif
but here myCPPfunc() is a normal C++ function with a class def inside - i.e. it was wrongly labeled as a C function.
What is the impact of this?
The main impact of this is that you cannot overload it, e.g. this is legal:
int myCPPfunc(int a);
int myCPPfunc(char a);
But this is not:
extern "C"
{
int myCPPfunc(int a);
int myCPPfunc(char a);
}
It is perfectly legitimate to have the implementation of an extern "C" function use arbitrary C++ features. What you can't do is have its interface be something you couldn't do in C, e.g. argument overloading, methods (virtual or otherwise), templates, etc.
Be aware that a lot of the "something you couldn't do in C" cases provoke undefined behavior rather than prompt compile errors.
This tells the C++ compiler that the functions declared in the header file are C functions.
http://www.parashift.com/c++-faq-lite/mixing-c-and-cpp.html#faq-32.2
This is exactly what extern "C" is for - it allows you to write a C++ function that can be called from C.
Essentially, that declaration is telling the C++ compiler that you want the C++ function myCPPfunc() to have an external interface that is linkable (and therefore callable) from C.
The implementation of the function is still C++ and can still use C++ features.
Typically, the declaration of the function in the header file might look more like:
#ifdef __cplusplus
extern "C" {
#endif
int myCPPfunc(some_arg_list....); /* a C++ function */
#ifdef __cplusplus
}
#endif
That lets the same header file be used by either the C++ compiler or the C compiler, and each will see it as declaring a C callable function.