日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程语言 > c/c++ >内容正文

c/c++

【深入理解C++】头文件防卫式声明

發(fā)布時間:2024/1/8 c/c++ 31 豆豆
生活随笔 收集整理的這篇文章主要介紹了 【深入理解C++】头文件防卫式声明 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

文章目錄

  • 1.extern "C" 的作用
  • 2.__cplusplus 的作用
  • 3.防止頭文件被重復(fù)包含
    • 3.1 #ifndef...#define...#endif
    • 3.2 #pragma once
    • 3.3 兩者區(qū)別

1.extern “C” 的作用

我們知道,C++ 支持函數(shù)重載,C 語言不支持函數(shù)重載。在下面的代碼中,我們用 extern "C" 修飾兩個重載的函數(shù),程序會報錯,說明被 extern "C" 修飾的代碼會按照 C 語言的方式去編譯。

#include <iostream> using namespace std;// 程序報錯,因?yàn)镃語言不允許函數(shù)重載 extern "C" {void func(){cout << "func()" << endl;}void func(int v){cout << "func(int v)" << endl;} }int main() {return 0; }

注意:如果函數(shù)同時有聲明和實(shí)現(xiàn),要讓函數(shù)聲明被 extern "C" 修飾,函數(shù)實(shí)現(xiàn)可以不修飾。

#include <iostream> using namespace std;// 程序不報錯,因?yàn)橐粋€按照C語言的方式去編譯,一個按照C++的方式去編譯 extern "C" void func(); void func(int v);int main() {func();func(10);return 0; }void func() {cout << "func()" << endl; }void func(int v) {cout << "func(int v)" << endl; }

輸出結(jié)果如下:

C++ 在調(diào)用 C 語言 API 時,需要使用 extern "C" 修飾 C 語言的函數(shù)聲明。

2.__cplusplus 的作用

只要是 C++ 文件,都會在最前面自動定義這個宏 #define __cplusplus,因此,我們可以通過使用宏 __cplusplus 來區(qū)分 C 或 C++ 環(huán)境。

舉例:在下面程序中,math.h 和 math.c 是我們自己編寫的第三方庫,在 test.c 和 test.cpp 中都可以成功調(diào)用我們的第三方庫。

math.h

#ifdef __cplusplus extern "C" { #endif // __cplusplusint sum(int v1, int v2);int delta(int v1, int v2);#ifdef __cplusplus } #endif // __cplusplus

math.c

#include "math.h"int sum(int v1, int v2) {return v1 + v2; }int delta(int v1, int v2) {return v1 - v2; }

test.c

#include "math.h" #include <stdio.h>int main() {printf("%d\n", sum(10, 20));printf("%d\n", delta(10, 20));return 0; }

test.cpp

#include "math.h" #include <iostream> using namespace std;int main() {cout << sum(50, 20) << endl;cout << delta(30, 20) << endl;return 0; }

3.防止頭文件被重復(fù)包含

3.1 #ifndef…#define…#endif

使用 #ifndef...#define...#endif 來防止頭文件的內(nèi)容被重復(fù)包含。

math.h

#ifndef __MATH_H #define __MATH_H#ifdef __cplusplus extern "C" { #endif // __cplusplusint sum(int v1, int v2);int delta(int v1, int v2);#ifdef __cplusplus } #endif // __cplusplus#endif // !__MATH_H

3.2 #pragma once

#pragma once 可以防止整個文件的內(nèi)容被重復(fù)包含。

math.h

#pragma once#ifdef __cplusplus extern "C" { #endif // __cplusplusint sum(int v1, int v2);int delta(int v1, int v2);#ifdef __cplusplus } #endif // __cplusplus

3.3 兩者區(qū)別

(1) #ifndef...#define...#endif 受 C/C++ 標(biāo)準(zhǔn)的支持,不受編譯器的任何限制。

(2) 有些編譯器不支持 #pragma once(較老編譯器不支持,如GCC 3.4版本之前),兼容性不夠好。

(3) #ifndef...#define...#endif 可以針對一個文件中的部分代碼,而 #pragma once 只能針對整個文件。

總結(jié)

以上是生活随笔為你收集整理的【深入理解C++】头文件防卫式声明的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。