从缺少 printf 语句输出C++调用 C API

Calling C APIs from C++ missing output of printf statements

本文关键字:C++ 调用 API 输出 语句 printf      更新时间:2023-10-16

让我们通过示例代码。

测试1.c

#include<stdio.h>
void ctest1(int *i)
{
   printf("This is from ctest1n"); // output of this is missing
   *i=15;
   return;
}

ctest2.c

#include<stdio.h>
void ctest2(int *i)
{
   printf("This is from ctest2n"); // output of this is missing
   *i=100;
   return;
}

Ctest.h

void ctest1(int *);
void ctest2(int *);

现在让我们从中制作 c 库

gcc -Wall -c ctest1.c ctest2.c
ar -cvq libctest.a ctest1.o ctest2.o

现在让我们制作基于cpp的文件,它将使用此c apis进度.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 API。但是缺少这些 printf 语句的输出。

我错过了什么?

对我来说效果很好(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/