C++ 虚函数
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