GCC C calls C + +

Source: Internet
Author: User

The road of programming is just beginning, the mistake inevitably, hoped everybody can point out.

Simply record the C file to invoke the CPP file, using the code to illustrate:

1 /*test.h*/2 #ifdef __cplusplus3 extern "C"4 {5 #endif6 intAddintXinty);7 #ifdef __cplusplus8 }9 #endifTen  One  A /*Test.cpp*/ -#include"test.h" -  the intAddintXinty) - { -     returnx+y; - } +  -  + /*main.c*/ A#include <stdio.h> at#include"test.h" -  - intMain () - { -     intD = Add (1,2); -printf"%d\n", d); in  -     return 0; to}

Command line: GCC main.c test.cpp

The only thing you need to know here is the following paragraph:

#ifdef __cplusplus
extern "C" {

A section of code

#ifdef __cplusplus

__cplusplus is a custom macro in CPP, the meaning of the above code is: if the macro __cplusplus is defined, then this paragraph is the CPP code, so add the extern "C" {and} to process the code in it.

The main purpose of extern "C" is to be able to correctly implement C + + code calls to other C language code. The addition of extern "C" instructs the compiler to compile this part of the code in C instead of C + +. Because C + + supports function overloading, the compiler compiles the function by adding the parameter type of the function to the compiled code, not just the function name, and the C language does not support the functions overloading, so the function of compiling C code does not take the parameter type of the function, generally only includes the function name.

GCC C calls C + +

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.