当前位置:首页 > IT技术 > 编程语言 > 正文

C++ extern关键字的理解
2022-03-06 18:03:35

@TOC

extern关键字理解

  • extern关键字可以置于变量和函数名前,以标示变量或函数定义在别的函数中,提示编译器遇到此变量时在其它模块中寻找定义
//contract.h
//
// Created by Administrator on 2022/3/6.
//

#ifndef CSTART01_CONTRACT_H
#define CSTART01_CONTRACT_H

extern int i;
extern int a[];

#endif //CSTART01_CONTRACT_H
//cpx.cpp
//
// Created by Administrator on 2022/3/6.
//
int i = 10;
int a[] = {1,2,3,4};
//main.cpp
#include<iostream>
#include "contract.h"
using namespace std;

int main()  {
    cout << "hello world" << endl;
    cout << i << endl;
    for (int j = 0; j < 3; ++j) {
        cout << a[j] << endl;
    }
}
  • extern"C"的作用是可以解析并执行C语言代码,C+函数重载的时候可能修改了函数的名称,C语言没有函数重载,下面是实际的例子
//test.c
#include "test.h"

void show(){
    printf("hello world");
}
//test.h
#pragma once //防止头文件重复编译

#include <stdio.h>//C language code
#ifndef CSTART01_TEST_H
#define CSTART01_TEST_H

void show();//global method

#endif //CSTART01_TEST_H
//main.cpp
#include<iostream>

using namespace std;

//按照C语言方式做连接
extern "C" void show();//表示在别的文件中去找show方法

int main()  {
    show();//C++中函数是可以重载的,编译器会改变函数的名称,这行代码会产生错误

    system("pause");//程序暂停,需要按任意键继续
    return EXIT_SUCCESS;
}
  • 下面是第2种实现方式
//main.cpp
#include<iostream>
#include "test.h"
using namespace std;

//按照C语言方式做连接
//extern "C" void show();//表示在别的文件中去找show方法

int main()  {
    show();//C++中函数是可以重载的,编译器会改变函数的名称,这行代码会产生错误

    system("pause");//程序暂停,需要按任意键继续
    return EXIT_SUCCESS;
}
//test.h
//
// Created by Administrator on 2022/3/6
//
#pragma once //防止头文件重复编译

//程序的作用是如果是C++代码就多加这么一行话extern "C"{}
#ifdef __cplusplus
extern "C" {
#endif
#include <stdio.h>//C language code

void show();//global method

#ifdef __cplusplus
}
#endif

本文摘自 :https://blog.51cto.com/u