tags:

views:

137

answers:

4

Here is the code:

#include <iostream>
using namespace std;

extern "C" void myCfunc();

int main()
{
    myCfunc();

    return 0;
}

// This will link as a C function.
void myCfunc()
{
    cout << "This links as a C function.\n";
}

It prints:

This links as a C function.

Why is the extern keyword used? What meaning does it have?

While we are at it, what is the mutable keyword?

mutable int i;

What is different between it and int i?

A: 

It just means that the body of the function is not in your source-file.

It is an hint for the linker/compiler that he knowns that the smbol/functionname exists and what the function returns/takes.

Quonux
+2  A: 

extern "C" basically tells the compiler to treat the declaration as if it were made in C, rather than C++, to avoid name mangling. (It gives it C linkage.)

mutable is used for class members. It allows the member to be modified even in functions marked as const:

struct foo
{
    mutable int bar;

    void baz(void) const
    {
        bar = 5; // can be changed anyway
    }
};
GMan
+1 since the answer is a) correct b) chosen correct by the OP and c) merits something more than a 0.
andand
A: 

extern "C" {} means that the symbol(s) it is applied to will have "external" linkage specification. What exactly this does varies based on operating system and linker. But the general idea is that giving something "C" linkage 'exports it' which allows the operating system to find the function by name in your library when it is loaded dynamically (i.e. a windows dll or a linux so) by another program. If you don't give something "C" linkage, it will typically get a "mangled" C++ name, making it impossible for the dynamic library loaded to find the symbol.

Without the "C", extern tells the compiler to expect to find the symbol in a different compilation unit (i.e. object file). These are resolved at link-time rather than load time.

SoapBox
A: 

It says to the compiler that this function is in library compiled by C, not C++, compiler.

In C++ one can overload functions, so when parsing, function names in C++ has some extra informations (e.g. number and type of parameters). On the other hand, in C usually name is transtaled into _name, and nothing more. Linker needs to know exact name of the function in the extern module so if the module is compiled in C, extern "C" tells that to the compiler.

mutable keyword has nothing to do with extern, so don't know why have you put that into this question. Anyway: mutable in a field of the class says that even if instance of this class is constant, mutable field can be changed.

Archie