让我们按示例代码进行操作。从C++调用C API缺少printf语句的输出
ctest1.c
#include<stdio.h>
void ctest1(int *i)
{
printf("This is from ctest1\n"); // output of this is missing
*i=15;
return;
}
ctest2.c
#include<stdio.h>
void ctest2(int *i)
{
printf("This is from ctest2\n"); // output of this is missing
*i=100;
return;
}
ctest.h
void ctest1(int *);
void ctest2(int *);
现在让我们从
gcc -Wall -c ctest1.c ctest2.c
ar -cvq libctest.a ctest1.o ctest2.o
使C库
现在让我们做,这将使用该类别中的API prog.cpp CPP基于文件
#include <iostream>
extern "C" {
#include"ctest.h"
}
using namespace std;
int main()
{
int x;
ctest1(&x);
std::cout << "Value is" << x;
ctest2(&x);
std::cout << "Value is" << x;
}
现在让我们用C库编译这个C++程序现在
g++ prog.cpp libctest.a
像
./a.out
运行
输出为: 值为5值为100
但是这里的值是正确的。这意味着他们已经正确地调用了c apis。但是这些printf语句的输出缺失。
我失踪了?
为什么在函数定义中使用'return'? – Himanshu
它在我的机器上正常工作。你用'./a.out'启动它吗?尝试在printf之后放置'fflush(stdout);'。 – Marian
它对我来说工作得很好。 输出是: 这是从ctest1 值是15This是从ctest2 值是100 – Mayank