面试-C++

C++ 虚函数

详见 虚函数表解析
有关虚函数的FAQ

extern c

Ref In c++ source, what is the effect of extern “C”
原问题是:

What exactly does putting extern “c” into C++ do?

For example:

extern "c" {
    void foo();
}

extern “c”是linkage specification。简而言之,就是c++程序使用的是老的c代码gcc编译的.a或.o库时,需要特殊声明这个是特殊链接。
为什么呢?

C++有function overloading 机制,而c没有。G++编译器在链接函数时,不仅考虑函数名作为函数调用的ID,还要考虑其他信息(参数,arguments),但是gcc却仅仅将函数名当作唯一ID。extern “C”就是告诉G++,应当按照gcc的方式调用已经编译为二进制的函数。

Eg.

C++ C混编

foo.c

#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
int foo() {
    printf("hello from c foo\n");
    return 0;
}

使用gcc编译:

$gcc -c foo.c
# will generate foo.o file
# archive into static linked file .a
$ar cr libfoo.a foo.o
# libfoo.a binary file

main1.cpp

#include <iostream>
extern "C" {
    int foo();
}
int main() {
    foo();
    return 0;
}

假如不使用extern “C”,会报错

undefined reference to `foo()’

编译:

$g++ -std=c++11 -o main -L. -lfoo

C++编译

当对foo.c使用g++编译时,就正常了。仅需对main.cpp修改:

int foo();
...

g++编译过程:

g++ -c foo.c main.cpp
g++ -std=c++11 -o mian foo.o main.o

多线程编程

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值