Ted's Blog

Happy coding

extern "C"

Ted posted @ 2008年8月12日 18:19 in 未分类 with tags extern c , 1855 阅读

时常在cpp的代码之中看到这样的代码:

以下是引用片段:
#ifdef __cplusplus
extern "C" {
#endif
//一段代码
#ifdef __cplusplus
}
#endif

  这样的代码到底是什么意思呢?首先,__cplusplus是cpp中的自定义宏,那么定义了这个宏的话表示这是一段cpp的代码,也就是说,上面的代码的含义是:如果这是一段cpp的代码,那么加入extern "C"{和}处理其中的代码。

  要明白为何使用extern "C",还得从cpp中对函数的重载处理开始说起。在c++中,为了支持重载机制,在编译生成的汇编码中,要对函数的名字进行一些处理,加入比如函数的返 回类型等等.而在C中,只是简单的函数名字而已,不会加入其他的信息.也就是说:C++和C对产生的函数名字的处理是不一样的.

  比如下面的一段简单的函数,我们看看加入和不加入extern "C"产生的汇编代码都有哪些变化:

以下是引用片段:
int f(void)
{
return 1;
}

  在加入extern "C"的时候产生的汇编代码是:

以下是引用片段:
.file "test.cxx"
.text
.align 2
.globl _f
.def _f; .scl 2; .type 32; .endef
_f:
pushl %ebp
movl %esp, %ebp
movl $1, %eax
popl %ebp
ret

  但是不加入了extern "C"之后

以下是引用片段:
.file "test.cxx"
.text
.align 2
.globl __Z1fv
.def __Z1fv; .scl 2; .type 32; .endef
__Z1fv:
pushl %ebp
movl %esp, %ebp
movl $1, %eax
popl %ebp
ret

  两段汇编代码同样都是使用gcc -S命令产生的,所有的地方都是一样的,唯独是产生的函数名,一个是_f,一个是__Z1fv。

  明白了加入与不加入extern "C"之后对函数名称产生的影响,我们继续我们的讨论:为什么需要使用extern "C"呢?C++之父在设计C++之时,考虑到当时已经存在了大量的C代码,为了支持原来的C代码和已经写好C库,需要在C++中尽可能的支持C,而 extern "C"就是其中的一个策略。

  试想这样的情况:一个库文件已经用C写好了而且运行得很良好,这个时候我们需要使用这个库文件,但是我们需要使用C++来写这个新的代码。如果 这个代码使用的是C++的方式链接这个C库文件的话,那么就会出现链接错误.我们来看一段代码:首先,我们使用C的处理方式来写一个函数,也就是说假设这 个函数当时是用C写成的:

以下是引用片段:
//f1.c
extern "C"
{
void f1()
{
return;
}
}

  编译命令是:gcc -c f1.c -o f1.o 产生了一个叫f1.o的库文件。再写一段代码调用这个f1函数:

以下是引用片段:
// test.cxx
//这个extern表示f1函数在别的地方定义,这样可以通过
//编译,但是链接的时候还是需要
//链接上原来的库文件.
extern void f1();
int main()
{
f1();
return 0;
}

  通过gcc -c test.cxx -o test.o 产生一个叫test.o的文件。然后,我们使用gcc test.o f1.o来链接两个文件,可是出错了,错误的提示是:

以下是引用片段:
test.o(.text + 0x1f):test.cxx: undefine reference to 'f1()'

  也就是说,在编译test.cxx的时候编译器是使用C++的方式来处理f1()函数的,但是实际上链接的库文件却是用C的方式来处理函数的,所以就会出现链接过不去的错误:因为链接器找不到函数。

  因此,为了在C++代码中调用用C写成的库文件,就需要用extern "C"来告诉编译器:这是一个用C写成的库文件,请用C的方式来链接它们。

  比如,现在我们有了一个C库文件,它的头文件是f.h,产生的lib文件是f.lib,那么我们如果要在C++中使用这个库文件,我们需要这样写:

以下是引用片段:
extern "C"
{
#include "f.h"
}

  回到上面的问题,如果要改正链接错误,我们需要这样子改写test.cxx:

以下是引用片段:
extern "C"
{
extern void f1();
}
int main()
{
f1();
return 0;
}

  重新编译并且链接就可以过去了.

  总结

  C和C++对函数的处理方式是不同的.extern "C"是使C++能够调用C写作的库文件的一个手段,如果要对编译器提示使用C的方式来处理函数的话,那么就要使用extern "C"来说明。

Avatar_small
james 说:
2020年11月18日 14:45

This platform seriously has some of the coolest and the most effective working tools and features ever. You can find them only at the platform of the <a href="https://it.altosplitpdf.com/">it.altosplitpdf.com</a> online. You can click on the link below in the description box.

Avatar_small
james 说:
2020年11月18日 14:46

This platform seriously has some of the coolest and the most effective working tools and features ever. You can find them only at the platform of the it.altosplitpdf.com online. You can click on the link below in the description box.

Avatar_small
kevin 说:
2020年11月28日 01:56

Students preparing for Mizoram Board 12th exams must solve previous year MBSE HSSLC question papers. Solving these Mizoram HSLC sample papers is much important to be familiar with exam pattern. These question papers will help students to understand the different types of question that do rounds in the Mizoram Mizo HSSLC Question paper 2021. These MBSE HSSLC question papers 2021 can be downloaded by clicking on the link mentioned below. Students are advised to solve the MBSE HSSLC model question papers 2021 within the stipulated time. It will improve their time management skills. Practising with MBSE HSSLC model questions papers will also aid students to prepare for the real and the bigger exams.

Avatar_small
Lagend SEO 说:
2020年12月06日 18:54

You have done a great job on this article. It's very readable and highly intelligent. You have even managed to make it understandable and easy to read. You have some real writing talent. Thank you. soap2day.name

Avatar_small
Lagend SEO 说:
2020年12月10日 19:14

That is the excellent mindset, nonetheless is just not help to make every sence whatsoever preaching about that mather. Virtually any method many thanks in addition to i had endeavor to promote your own article in to delicius nevertheless it is apparently a dilemma using your information sites can you please recheck the idea. thanks once more. APC router password

Avatar_small
LEGEND SEO 说:
2020年12月23日 19:01

I can’t imagine focusing long enough to research; much less write this kind of article. You’ve outdone yourself with this material. This is great content. casino online canada

Avatar_small
LEGEND SEO 说:
2020年12月26日 21:20

This is truly a great read for me. I have bookmarked it and I am looking forward to reading new articles. Keep up the good work!. kasyna online

Avatar_small
LEGEND SEO 说:
2020年12月27日 19:01 I’m going to read this. I’ll be sure to come back. thanks for sharing. and also This article gives the light in which we can observe the reality. this is very nice one and gives indepth information. thanks for this nice article... kasyno bez depozytu
Avatar_small
LEGEND SEO 说:
2020年12月28日 16:53

Thanks for taking the time to discuss this, I feel strongly about it and love learning more on this topic. If possible, as you gain expertise, would you mind updating your blog with extra information? It is extremely helpful for me. woodworking business

Avatar_small
Tube Mastery and Mon 说:
2021年4月01日 20:12

I think about it is most required for making more on this get engaged

Avatar_small
apartment in budapes 说:
2021年4月05日 14:21

I was very pleased to find this site.I wanted to thank you for this great read!! I definitely enjoying every little bit of it and I have you bookmarked to check out new stuff you post.

Avatar_small
CPI 说:
2021年6月10日 14:18

All the contents you mentioned in post is too good and can be very useful. I will keep it in mind, thanks for sharing the information keep updating, looking forward for more posts.Thanks

Avatar_small
John 111 说:
2021年6月25日 23:28

Great job for publishing such a beneficial web site. Your web log isn’t only useful but it is additionally really creative too. 토토

Avatar_small
Buy clubhouse follow 说:
2021年8月04日 16:27

I like viewing web sites which comprehend the price of delivering the excellent useful resource free of charge. I truly adored reading your posting. Thank you!

Avatar_small
Top SEO 说:
2021年8月06日 00:56

Great post i must say and thanks for the information. Education is definitely a sticky subject. However, is still among the leading topics of our time. I appreciate your post and look forward to more. centre de formation pour les entreprise

Avatar_small
mis webmail 说:
2021年12月25日 15:41

The content which they provide at is the best part of them. Seriously I have never seen something like this befoe. No complaints rom them!

Avatar_small
www.signnow.com 说:
2021年12月28日 17:57

some people want to make two pdf files together and they do not find a way to do that. Now with the aid of anybody can do it. It is done in seconds and without any cost.

Avatar_small
juniper hill showfla 说:
2021年12月29日 15:58

This website and I conceive this internet site is really informative ! Keep on putting up!

Avatar_small
ssali 说:
2022年9月26日 06:04

Great stuff. i am going to bookmark it, if you are looking for bluetooth fm transmitter, xiaomi redmi airdots, wifi versterker, beste wifi versterker, nokia 105, smartphone holder in Netherlands, get in touch with us.

 

Avatar_small
Immigration Lawyer i 说:
2023年7月07日 23:36

There are several dissertation internet sites on-line as you are get naturally written about as part of your internet site.

Avatar_small
mygdkitchen.com 说:
2023年12月13日 22:38

I recently experienced the culinary delights at GD Kitchen, and it was a gastronomic journey like no other!

Avatar_small
Twin Rocks Water 说:
2023年12月21日 19:30

Rock Springs Water: Immerse yourself in the pure essence of refreshment with our exceptional Rock Springs Water. Sourced from nature's pristine springs, each sip embodies crisp purity. Elevate your hydration experience with the natural goodness of Rock Springs Water, where every drop tells a tale of pristine quality.

Avatar_small
減脂 说:
2024年1月03日 21:55

Wearing a mask isn't just about following rules or trends—it's about keeping yourself and others safe. Masks act as a shield, protecting us from inhaling harmful particles, such as viruses and bacteria, that might be present in the air. When we wear masks, we reduce the chances of spreading these particles, which is crucial in preventing the spread of diseases like COVID-19.

Avatar_small
Brown Stone Law 说:
2024年1月20日 12:47

Elevate your legal strategy with Pennsylvania's top federal appeal lawyer. Our distinguished attorney brings unparalleled expertise and a proven track record in navigating federal appeals. Trust in our commitment to excellence as we provide strategic guidance and assertive representation to secure optimal outcomes for your case. Choose the pinnacle of legal advocacy for your federal appeal needs.

Avatar_small
was kostet eine webs 说:
2024年1月29日 19:59

Blackrabbyt is a Vienna-based creative digital agency with a passion for constantly pushing the boundaries of creativity and technical innovation.
We develop, invigorate and let you grow, and we do this by making your success story tangible digitally, finding your unique solution and conscientiously achieving the attention you want.

Avatar_small
SEO 说:
2024年1月30日 03:49

Thanks for the blog post buddy! Keep them coming... employee motivation and engagement strategies


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter