C++中写C代码

#include <iostream>
#include <stdio.h>
#include "For.c"
extern "C" {
//告诉编译器 使用C语言编译 不然会报方法未定义异常
#include "point.h"
}
#ifdef __cplusplus
extern "C" { // 告诉编译器下列代码要以C链接约定的模式进行链接
#endif
void testFor() {
    int sum = 0;
    for (int x = 1; x <= 100; ++x) {
        sum += x;
    }
    printf("1~100的累加和 = %d", sum);
}

#ifdef __cplusplus
}
#endif

//extern "C" void testFor(int x);

int main() {
  forTest();
  testFor();
}

void testFor(int x) {
    int sum = 0;
    for (; x <= 100; ++x) {
        sum += x;
    }
    cout << "1~100的累加和 = %d" << sum << endl;
}

For.c

#include <stdio.h>

void forTest() {
    int x = 1, sum = 0;
    for (int x = 1; x <= 100; ++x) {
        sum += x;
    }
    printf("1~100的累加和 = %d", sum);
}

point.h

void getPoint(int a);
void showPoint();

point.c

#include <stdio.h>
void getPoint(int a) {
    int *pa = &a;
    printf("pa===1===%d,%d\n", pa, *pa);
    *pa = 6;
    printf("pa===2===%d,%d\n", pa, *pa);
}

总结:
1.#ifdef __cplusplus中的代码 须符合C语言的规范,cout使用报错
2.extern “C” 方法名 就是让C++连接器能过类似于_foo来查找此函数,而非类似于_foo_int这样的符号。

猜你喜欢

转载自blog.csdn.net/qq_20330595/article/details/82013029