一个没有#include <stdio.h>的简单C程序

ant*_*a40 2 c assembly printf mingw inline-assembly

如何在不包含stdio.h的情况下直接调用"printf"?

我在这里找到了一个有趣的教程:http:
//www.halcode.com/archives/2008/05/11/hello-world-c-and-gnu-as/

所以,这是我的尝试:

int main(){
 char ss[] = "hello";

 asm (
  "pushl %ebp ;"
  "movl %esp, %ebp ;"
  "subl $4, %esp ;"
  "movl $ss, (%esp) ;"
  "call _printf ;"
  "movl  $0, %eax ;"
  "leave ;"
  "ret ;"
 );

 return 0;
}
Run Code Online (Sandbox Code Playgroud)

我正在使用MinGW 4.4,这是我如何编译它:

gcc -c hello.c -o hello.o
ld hello.o -o hello.exe C:/mingw/lib/crt2.o C:/mingw/lib/gcc/mingw32/4.4.0/crtbegin.o C: /mingw/lib/gcc/mingw32/4.4.0/crtend.o -LC:/mingw/lib/gcc/mingw32/4.4.0 -LC:/ mingw/lib -lmingw32 -lgcc -lmsvcrt -lkernel32

不幸的是,它失败了:

hello.o:hello.c :(.text + 0x26):对`ss'的未定义引用

如何解决这个问题?

P S*_*ved 9

您可以将声明复制printf到您的程序中.在C中,包括其他文件只是将其文本复制粘贴到您的程序中.因此,您可以通过自己进行复制粘贴来完成这项工作.

extern int printf (const char* format, ...);

int main()
{
  printf("Hello, world!\n");
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

链接器肯定会在库中找到正确的定义,默认情况下,程序链接到该库.