从缺少 printf 语句输出C++调用 C API
Calling C APIs from C++ missing output of printf statements
让我们通过示例代码。
测试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/
相关文章:
- 什么时候调用组成单元对象的析构函数
- 对RValue对象调用的LValue ref限定成员函数
- 为什么使用 "this" 指针调用派生成员函数?
- 函数调用中参数的顺序重要吗
- OpenGL - 在抛出"__gnu_cxx::recursive_init_error"实例后终止调用?
- 基于另一个成员参数将函数调用从类传递给它的一个成员
- 为什么我的C#代码在调用回C++COM直到Task时会暂停.等待/线程.加入
- 在c++类上调用void函数
- 为什么 std::unique 不调用 std::sort?
- 调用专用模板时出错"no matching function for call to [...]"
- 选择要调用的构造函数
- C++为什么尽管我调用了void函数,它却不起作用
- 构造函数正在调用一个使用当前类类型的函数
- 变量没有改变?通过向量的函数调用
- 没有为自己的结构调用列表推回方法
- 调用'begin(int [n])'没有匹配函数
- 什么时候调用析构函数
- 如何用参数值调用函数(仅在运行时已知)
- std::cout.imbue()多重调用
- 函数何时会在c++中包含stack_Unwind_Resume调用