I use Rust to call a C function with a loop (for
or while
), which uses printf
function to display something, but the C function doesn't display any output from printf
.
C code:
#include <stdio.h>
#include <unistd.h>
void print_c() {
int s = 3;
while (1) {
printf("%d\n", s);
sleep(1);
}
}
However, when using C++, output is successfully generated.
C++ code:
#include <iostream>
#include <stdint.h>
#include <unistd.h>
extern "C" {
int print_it(int32_t num) {
while (1) {
std::cout << num << std::endl;
sleep(1);
}
}
}
C is packaged as a shared library named "cthread". C++ is named "cppthread".
This is the Rust calling the C library:
#[link(name = "cthread")]
extern "C" {
fn print_c();
}
fn main() {
unsafe { print_c() };
}
And the Rust calling the C++ library:
#[link(name = "cppthread")]
extern "C" {
fn print_it();
}
fn main() {
unsafe { print_it() };
}
std::endl
, which has an implicit flush to stdout (that is the reason the use ofstd::endl
is discouraged). Forcing a similar flush in the C version with afflush(stdout)
might be the cause.