2015-01-02 38 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

錯字,而不是問號,但逗號... –