x86_64架构下C语言逆波兰计算器未定义符号错误求助
解决逆波兰计算器的x86_64架构未定义符号链接错误
你遇到的链接错误原因很直接——代码中仅声明了getop、push、pop三个函数,但没有提供它们的具体实现,链接器无法找到这些符号的定义,因此报错。
以下是补充完整实现后的可编译代码,对应《C程序设计语言》中的标准实现:
#include <stdio.h> #include <stdlib.h> #include <ctype.h> #define MAXOP 100 #define NUMBER '0' #define MAXVAL 100 // 栈的最大深度 int sp = 0; // 栈顶指针 double val[MAXVAL]; // 栈数组 // 函数声明 int getop(char[]); void push(double); double pop(void); int main() { int type; double op2; char s[MAXOP]; while ((type = getop(s)) != EOF) { switch (type) { case NUMBER: push(atof(s)); break; case '+': push(pop() + pop()); break; case '*': push(pop() * pop()); break; case '-': op2 = pop(); push(pop() - op2); break; case '/': op2 = pop(); if (op2 != 0.0) push(pop() / op2); else printf("error: Zero divisor\n"); break; case '\n': printf("\t%.8g\n", pop()); break; default: printf("error: unknown command %s \n", s); break; } } return 0; } // 压栈函数实现 void push(double f) { if (sp < MAXVAL) val[sp++] = f; else printf("error: stack full, can't push %g\n", f); } // 弹栈函数实现 double pop(void) { if (sp > 0) return val[--sp]; else { printf("error: stack empty\n"); return 0.0; } } // 获取操作符或数字的函数实现 int getop(char s[]) { int i, c; // 跳过空白字符 while ((s[0] = c = getchar()) == ' ' || c == '\t') ; s[1] = '\0'; // 不是数字或小数点,直接返回该字符 if (!isdigit(c) && c != '.') return c; i = 0; // 收集整数部分 if (isdigit(c)) while (isdigit(s[++i] = c = getchar())) ; // 收集小数部分 if (c == '.') while (isdigit(s[++i] = c = getchar())) ; s[i] = '\0'; // 把多余读取的字符放回输入流 if (c != EOF) ungetc(c, stdin); return NUMBER; }
编译与运行说明
将上述代码保存为reversepolish.c,执行编译命令:
cc reversepolish.c -o reversepolish
编译通过后,运行程序即可输入逆波兰表达式计算,比如输入3 4 +后按回车,会输出7。
如果要拆分文件(比如把栈操作和getop单独放在不同文件),需同时编译所有相关文件:
# 假设拆分后有reversepolish.c、stack.c、getop.c三个文件 cc reversepolish.c stack.c getop.c -o reversepolish
原问题代码
#include <stdio.h> #include <stdlib.h> #define MAXOP 100 #define NUMBER '0' // functions as external thing int getop(char[]); void push(double); double pop(void); int main() { // defining variables n stuff int type; double op2; // operand 2 char s[MAXOP]; while ((type = getop(s)) != EOF) { switch (type) { case NUMBER: push(atof(s)); break; case '+': push(pop() + pop()); break; case '*': push(pop() * pop()); break; case '-': op2 = pop(); push(pop() - op2); break; case '/': op2 = pop(); if (op2 != 0.0) push(pop() / op2); else printf("error: Zero divisor\n"); break; case '\n': printf("\t%.8g\n", pop()); break; default: printf("error:unknown command %s \n", s); break; } } return 0; }
原终端输出
cc reversepolish.c -o reversepolish Undefined symbols for architecture x86_64: "_getop", referenced from: _main in reversepolish-fc0241.o "_pop", referenced from: _main in reversepolish-fc0241.o "_push", referenced from: _main in reversepolish-fc0241.o ld: symbol(s) not found for architecture x86_64 clang: error: linker command failed with exit code 1 (use -v to see invocation) make: *** [reversepolish] Error 1
内容的提问来源于stack exchange,提问作者Frost
相关产品推荐
相关产品推荐

