extern "C"
时常在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"来说明。
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.
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.
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.
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
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
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
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
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
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
2021年4月01日 20:12
I think about it is most required for making more on this get engaged
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.
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
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. 토토
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!
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
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!
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.
2021年12月29日 15:58
This website and I conceive this internet site is really informative ! Keep on putting up!
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.
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.
2023年12月13日 22:38
I recently experienced the culinary delights at GD Kitchen, and it was a gastronomic journey like no other!
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.
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.
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.
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.
2024年1月30日 03:49
Thanks for the blog post buddy! Keep them coming... employee motivation and engagement strategies
2024年6月27日 13:58
Discover professional cuticle care techniques at our salon. Our expert technicians use advanced methods to ensure healthy, beautiful cuticles that enhance the look of your nails. Book your appointment today to experience top-notch cuticle care techniques.
2024年7月15日 18:50
Looking for the best spray tan near me? Our salon offers top-quality, natural-looking tans customized to your skin tone. Enjoy a flawless, streak-free glow with our expert technicians. Book your appointment now!
2024年8月30日 22:11
Hello! I am Shamikh, an SEO expert with 3+ years of experience ain digital marketing. I specialize in local SEO, on-page and off-page optimization, technical SEO and backlink building. I have successfully ranked 250+ businesses on the first page of Google using the latest trends and algorithms. Let's work together to improve your online presence and achieve your business goals. Feel free to contact me for any collaboration ideas!
2024年11月20日 21:24
Mobile fake tan brings the perfect sun-kissed glow directly to your door. Expert technicians use high-quality, customized products to deliver a streak-free, natural-looking tan tailored to your skin tone. Ideal for those with busy schedules or seeking the convenience of a professional tan at home, mobile fake tan offers a luxurious, UV-free tanning experience in the comfort of your own space.
2024年11月26日 13:33
I'd like to give this website called Fields data Automation Bots a 5.5. The finest thing about this website is the level of service they give. There are no drawbacks!
2024年12月22日 18:41
Looking for excitement? 온라인슬롯 offers an unbeatable gaming experience!
2024年12月26日 20:24
Every piece of Aari work tells a story of dedication and exceptional craftsmanship.
2024年12月29日 19:23
Bitcoin TX Accelerate is a high-quality service designed to expedite the confirmation times of your Bitcoin transfers, ensuring swift transaction processing. btc accelerator