2015-01-02 39 views
4

让我们按示例代码进行操作。从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语句的输出缺失。

我失踪了?

+0

为什么在函数定义中使用'return'? – Himanshu

+3

它在我的机器上正常工作。你用'./a.out'启动它吗?尝试在printf之后放置'fflush(stdout);'。 – Marian

+2

它对我来说工作得很好。 输出是: 这是从ctest1 值是15This是从ctest2 值是100 – Mayank

回答

4

它适用于我(OSX 10.8,LLVM 6.0)。

您可能已通过添加printfs修改了您的代码,并忘记重新生成相应的库。您应该使用r(替换选项)代替q

但是在混合输入/输出层时要小心,最好要求两者同步。调用ios_base :: sync_with_stdio(1)让它们一起工作,请参阅http://www.cplusplus.com/reference/ios/ios_base/sync_with_stdio/

+0

错字,而不是问号,但逗号... –