some special cases of "extern" in C

来源:互联网 发布:sqlserver 优势 编辑:程序博客网 时间:2024/05/19 19:34

we can use extern to specify that a symbol is defined somewhere else, e.g

a.c:

extern int a;

b.c

int a;

When compiling a.c compiler knows that a is not defined in a.c then when linking it will search for it in other object file.

And there are some very werid cases where extern can be used.

1. Change data view

//a.c#include <stdio.h>extern struct s{    char a[4];}c;extern void test();int main(){    test();    printf("%s",c.a);    return 0;}

//b.cstruct a{    int b;}c;void test(){    c.b = 0x31313131;}

c declared in a.c is an extern variant and it is actually defined in the b.c. but they have different data view in a.c and b.c, while their data size is same. we can use this method to change data view in different source file and functions.

2. c data structure altered to c++ data structure

this example is more werid in the real application(learn it from ibm complier source code)

//a.cpp. c++ data structure defined with class#include <iostream>using namespace std;struct sb{    int a;    int b;};class A:public sb{};extern "C" void test(A a){    cout<<"test"<<endl;    cout<<a.a<<a.b<<endl;}

//b.c. c data structure define with struct#include <stdio.h>struct sc{    int a;    int b;};struct sc cc[2]={{1,2},{2,1}};extern void test(struct sc * psc);int main(){    test(&cc[0]);}

in b.c we want to pass an parameter defined with c data structure but the interface is defined in c++ in a.c then we can compiler the interface defined in c++ with extern "C" and compiler will compiler the c++ code with c regulations.

since c++ class defined in a.c does not have virtual functions, its memory layout is the same with memory layout of c data structure defined in b.c. so when we pass a pointer that points to the address of the c data structure to the c++ interface it can accept it and treat the memory layout as the class memory layout.

PS: if the class has virtual functions then there is a virtual pointer at the head of the memory layout of the class object.e.g.

$1 = {_vptr.T = 0x100009d8, b = -5992272, c = -134155168}

原创粉丝点击