Windows下使用TCC以底层方式向stdout写入字符序列的问题
问题解决:Windows下用TCC底层写入stdout并查看汇编代码
1. 现有代码无输出的原因及修复
你的代码没有输出的核心问题是buf_sz始终为0,导致write调用写入的字节数为0。正确的字节长度应该是从pos到缓冲区末尾的字符数,即sizeof(buf) - pos。
修正后的代码:
#include <stdio.h> #include <io.h> #include <stdint.h> void dumpDec(uint16_t x) { char buf[32]; int pos = sizeof(buf) - 1; buf[pos] = '\n'; do { pos--; buf[pos] = x % 10 + '0'; x /= 10; } while (x > 0); size_t write_len = sizeof(buf) - pos; write(1, &buf[pos], write_len); } int main() { dumpDec(2048); return 0; }
编译运行后就能正常输出2048加换行。
2. Windows下更底层的写入方式
如果要使用更贴近Windows系统底层的API,可以直接调用WriteFile(Win32原生函数),它比<io.h>封装的write更接近系统调用:
#include <windows.h> #include <stdint.h> void dumpDec(uint16_t x) { char buf[32]; int pos = sizeof(buf) - 1; buf[pos] = '\n'; do { pos--; buf[pos] = x % 10 + '0'; x /= 10; } while (x > 0); size_t write_len = sizeof(buf) - pos; DWORD bytes_written; HANDLE stdout_handle = GetStdHandle(STD_OUTPUT_HANDLE); WriteFile(stdout_handle, &buf[pos], write_len, &bytes_written, NULL); } int main() { dumpDec(2048); return 0; }
编译时需要链接kernel32.lib,TCC编译命令:
tcc.exe main.c -lkernel32
3. 查看汇编代码的方法
用TCC生成汇编代码,只需添加-S参数:
tcc.exe -S main.c
执行后会生成main.s文件,里面就是编译后的汇编代码,可直接查看底层调用的实现细节。
内容的提问来源于stack exchange,提问作者Thomas S.
相关产品推荐
相关产品推荐

