How to use C ++ to call the C-Linked Library

Source: Internet
Author: User

The C ++ programming language is widely used and has flexible application methods. It supports multiple programming styles and helps us solve many problems easily. For example, the specific operation method for C ++ to call the C link library introduced today is a classic example, which allows you to fully understand the concept.

  • Detailed description of how C ++ generates random numbers
  • Practical application skills of C ++ linked list operations
  • A Brief Introduction to the C ++ Operating Mechanism
  • Basic concepts of C ++ cyclic statements
  • Application Methods for C ++ class members

C ++ calls the C link library, but it actually calls C ++ relative to C. Because C ++ is inherently backward compatible with C's personal opinions ).

However, due to the different design of the compiler, some problems may occur, such as: In the middle part, there is an undefined reference to 'helloc () ', helloC () is my function in the C-Linked Library)

Simply put, the reason is that the function name may change to _ helloC () after the unprocessed C code is compiled, but the function name after the C ++ compilation is not like this, so it is not correct.

You need to add extern "C" to the include c file"

In the exercise, three files are written: c. h c. c cpp. The first two files are compiled as C-linked libraries, and cpp. cpp uses C. It verifies that C ++ calls the C link library to access the global variables of C.

C. h:

 
 
  1. #include "stdio.h"  
  2. void helloC();  
  3. int abc = 1; 

C. c:

 
 
  1. #include <stdio.h> 
  2. #include "c.h"  
  3. void helloC(){  
  4. printf("I am Kenko");  

Cpp. cpp: (focus on include)

 
 
  1. #include <iostream> 
  2. using namespace std;  
  3. extern "C" {  
  4. #include "c.h"  
  5. }  
  6. int main(){  
  7. helloC();  
  8. cout<<abc<<endl;  
  9. return 0;  

This section describes how C ++ calls the C-Linked Library.

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.