C++學習——在C文件中調用C++文件中的函數


1.CPP文件中的內容

#include "mytest.h"
#include <iostream>

using namespace std;

int add(const int a, const int b)
{
    cout << "a=" << a << endl;
    cout << "b=" << b << endl;
    return (a + b);
}

2.頭文件中的內容

在函數聲明時添加extern "C",就可以在C中調用。為了同時可以在C++中調用,可以寫成下面這樣。

#ifdef __cplusplus
extern "C"
{
#endif

    int add(const int a, const int b);

#ifdef __cplusplus
}
#endif

3.C文件中的內容

#include <stdio.h>
#include <stdlib.h>
#include "mytest.h"

void main() {
    printf("%d\n", add(1, 2));
}

4.運行結果

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM