Mysterious cgo behavior: C "hello world" printf doesn't print

2,264 views
Skip to first unread message

Hai Thanh Nguyen

unread,
May 11, 2015, 10:04:00 AM5/11/15
to golan...@googlegroups.com
I tried running this dummy cgo program, it compiles but for some reason when running this obvious program, it doesn't print out anything:
package main

/*
#include <stdio.h>
#include <stdlib.h>

void myprint() {
 printf("Hello world");
}
*/

import "C"

func main
() {
 C
.myprint()
}

However if I try this more complex program from the wiki, it works and prints the string "Hello from stdio" out normally
package main

/*
#include <stdio.h>
#include <stdlib.h>

void myprint(char* s) {
 printf("%s", s);
}
*/

import "C"
import "unsafe"

func main
() {
 cs
:= C.CString("Hello from stdio\n")
 C
.myprint(cs)
 C
.free(unsafe.Pointer(cs))
}

That's super weird, an obvious program doesn't work, a more complicated one works.
I tried a lot of different ways to figure out why, but so far unable to. Could someone shed some light on why? Could this be a bug or something? It acts as if cgo says "this C code is too simple, let me just omit it.". (I also tried writing the program in C only, compile with gcc and of course it runs as expected).

Hai Thanh Nguyen

unread,
May 11, 2015, 10:05:22 AM5/11/15
to golan...@googlegroups.com
Note that my machine on ArchLinux 64 bit. Not sure if it's like that on other platforms.

Jan Mercl

unread,
May 11, 2015, 10:16:17 AM5/11/15
to golan...@googlegroups.com

n Mon, May 11, 2015 at 4:04 PM Hai Thanh Nguyen <phai...@gmail.com> wrote:

> I tried running this dummy cgo program, it compiles but for some
> reason when running this obvious program, it doesn't print out anything:

> printf("Hello world");

Add \n to the end of the string to flush the C's stdout buffer.

-j

Hai Thanh Nguyen

unread,
May 11, 2015, 10:25:30 AM5/11/15
to golan...@googlegroups.com
Oh nice, thank you. Sometimes I'm just an idiot :v.
Reply all
Reply to author
Forward
0 new messages