利用預編譯解決C/C++重複定義的錯誤 -2020.09.13

利用預編譯解決C/C++重複定義的錯誤 -2020.09.13

我們現在有main.c和function.h兩個文件

main.c

#include <stdio.h>

#include "function.h"

int main() {
    printf("Hello, World!\n");
    printf("\t1+2+...+100\n"sum(100));
    return 0;
}

int sum(int n) {
    int res = 0;
    for (int i = 0; i < n; ++i) {
        res += i;
    }
    return res;
}

function.h

//#ifndef __SUM_H
//#define __SUM_H

int sum(int n);
int A = 0;

//#endif

我們使用命令gcc main.c -o hello,再使用ls,可以看到當前目錄下已經生成了hello.exe

然後我們再使用命令.\hello.exe運行程序,.\表示當前目錄

到目前為止都沒什麼不對的地方,現在我們添加一個function2.h,並在main.c中引入function2.h

function2.h的內容如下

#include "function.h"

main.c引入部分修改為

#include <stdio.h>

#include "function.h"
#include "function2.h"

我們再次使用命令gcc main.c -o hello,發現出現了報錯信息redefinition

意思就是重複定義了變量A,那麼我們需要在function.h中加入預編譯指令#ifndef #define #endif,

這樣可以有效防止重複定義或者重複包含的問題,我們將function.h中的三條預編譯指令解注釋

function.h修改為

#ifndef __SUM_H
#define __SUM_H

int sum(int n);
int A = 0;

#endif

我們再次使用命令gcc main.c -o hello,發現編譯正確通過了,再次運行程序

結果正確,因此在規範的開發當中我們需要使用#ifndef #define #endif來防止重複定義的問題