Jeegar Patel
Jeegar Patel

Reputation: 27210

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

Lets go by example code.

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 *);

Now lets make c library from that

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

Now lets make cpp based file which will use this c apis prog.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;

}

Now lets compile this c++ program with C library

g++ prog.cpp libctest.a

Now run it like

./a.out

Output is : Value is5Value is100

But here values are correct. It means they have called c apis correctly. But output of those printf statements are missing.

What i am missing?

Upvotes: 4

Views: 187

Answers (1)

Jean-Baptiste Yun&#232;s
Jean-Baptiste Yun&#232;s

Reputation: 36401

It works well for me (OSX 10.8, LLVM 6.0).

You may have modified your code by adding printfs and forget to regenerate your library accordingly. You should use r (replace option) in place of q.

But be careful when mixing both input/output layers, it is better to ask for synchronization of both. Call ios_base::sync_with_stdio(1) to get them work well together, see http://www.cplusplus.com/reference/ios/ios_base/sync_with_stdio/

Upvotes: 4

Related Questions