讓我們按示例代碼進行操作。從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