GCC编译并行端口脉冲控制C代码出现错误求助
解决GCC编译并行端口步进电机控制代码的错误
问题概述
在Debian 12(Bookworm)系统中,编译用于通过并行端口控制步进电机的C文件primeroscomandos.c时,执行gcc primeroscomandos.c出现编译错误,错误包含非法字符、perror函数参数指针类型不兼容等问题。
原代码
#include <stdio.h> #include <stdlib.h> #include <sys/io.h> #include <unistd.h> #define BASEPORT 0x378 int main() { if(ioperm(BASEPORT, 3, 1)) { perror(“ioperm”); return 1; } outb(0x01, BASEPORT); usleep(100000); outb(0x02, BASEPORT); usleep(1000000); outb(0x00, BASEPORT); if(ioperm(BASEPORT, 3, 0)) { perror(“ioperm”); return 1; } return 0; }
编译错误信息
primeroscomandos.c: In function ‘main’: primeroscomandos.c:9:33: error: stray ‘\342’ in program 9 | if(ioperm(BASEPORT,3,1)){perror(<U+201C>ioperm<U+201D>); | ^~~~~~~~ primeroscomandos.c:9:40: error: stray ‘\342’ in program 9 | if(ioperm(BASEPORT,3,1)){perror(<U+201C>ioperm<U+201D>); | ^~~~~~~~ primeroscomandos.c:9:34: warning: passing argument 1 of ‘perror’ from incompatible pointer type [-Wincompatible-pointer-types] 9 | if(ioperm(BASEPORT,3,1)){perror(“ioperm”); | ^~~~~~ | | | int (*)(long unsigned int, long unsigned int, int) In file included from primeroscomandos.c:1: /usr/include/stdio.h:804:33: note: expected ‘const char *’ but argument is of type ‘int (*)(long unsigned int, long unsigned int, int)’ 804 | extern void perror (const char *__s); | ~~~~~~~~~~~~^~~ primeroscomandos.c:20:33: error: stray ‘\342’ in program 20 | if(ioperm(BASEPORT,3,0)){perror(<U+201C>ioperm<U+201D>); | ^~~~~~~~ primeroscomandos.c:20:40: error: stray ‘\342’ in program 20 | if(ioperm(BASEPORT,3,0)){perror(<U+201C>ioperm<U+201D>); | ^~~~~~~~ primeroscomandos.c:20:34: warning: passing argument 1 of ‘perror’ from incompatible pointer type [-Wincompatible-pointer-types] 20 | if(ioperm(BASEPORT,3,0)){perror(“ioperm”); | ^~~~~~ | | int (*)(long unsigned int, long unsigned int, int) /usr/include/stdio.h:804:33: note: expected ‘const char *’ but argument is of type ‘int (*)(long unsigned int, long unsigned int, int)’ 804 | extern void perror (const char *__s); | ~~~~~~~~~~~~^~~
错误原因分析
所有错误的根源是代码中使用了全角中文引号“”,而非C语言要求的半角英文引号""。编译器无法识别全角引号,会将其解析为非法的ASCII转义字符(如\342),同时误把引号包裹的ioperm识别为函数指针,而非字符串常量,导致perror参数类型不兼容。
修复后的代码
将所有全角引号替换为半角引号即可解决问题:
#include <stdio.h> #include <stdlib.h> #include <sys/io.h> #include <unistd.h> #define BASEPORT 0x378 int main() { if(ioperm(BASEPORT, 3, 1)) { perror("ioperm"); return 1; } outb(0x01, BASEPORT); usleep(100000); outb(0x02, BASEPORT); usleep(1000000); outb(0x00, BASEPORT); if(ioperm(BASEPORT, 3, 0)) { perror("ioperm"); return 1; } return 0; }
编译与运行说明
- 编译命令:
gcc primeroscomandos.c -o primeroscomandos - 由于
ioperm需要直接访问硬件端口,必须以root权限运行程序:sudo ./primeroscomandos
内容的提问来源于stack exchange,提问作者M M
相关产品推荐
相关产品推荐

