some special cases of "extern" in C

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.c
struct 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}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值