SDCC编译时合法指针定义出现语法错误问题求助
Hey there! Let's break down this SDCC syntax error you're facing—it's a common cross-compiler pitfall, especially when moving code from Keil to SDCC.
First, let's recap the issue
You're getting a syntax error: token -> 'unsigned' ; column 10 on this line:
unsigned char * buf = (unsigned char *)pbuf;
Where pbuf is already an unsigned char* parameter. The line looks valid at first glance, so let's dig into the most likely causes.
Top 3 fixes to try
1. Move variable declarations to the start of your code block
SDCC defaults to strict C89 compliance, which requires all variable declarations to happen at the very beginning of a code block (before any executable statements). Keil often enables C99 by default, which lets you declare variables anywhere in the code.
For example, this will fail in SDCC:
void your_function(unsigned char *pbuf) { some_function_call(); // Executable statement first unsigned char *buf = pbuf; // Declaration after code = syntax error }
Fix it by moving the declaration to the top:
void your_function(unsigned char *pbuf) { unsigned char *buf; // Declare all variables first some_function_call(); buf = pbuf; // Assign later }
2. Remove the redundant type cast
Since pbuf is already an unsigned char*, the cast (unsigned char *) is unnecessary. While this shouldn't technically cause a syntax error, SDCC can be picky about redundant syntax. Simplify the line to:
unsigned char * buf = pbuf;
Or if you moved the declaration to the top, just buf = pbuf; as above.
3. Check for syntax errors in the lines before
Compilers often report errors on the line where they finally get confused, not where the actual mistake is. Double-check the 2-3 lines before your problematic code:
- Did you forget a semicolon at the end of a statement?
- Is there a mismatched curly brace or parenthesis?
- Did you end a preprocessor directive incorrectly?
A missing semicolon on the line before can make the compiler interpret your variable declaration as part of the previous statement, leading to a misleading syntax error.
Why this happens
Keil µVision is more forgiving with modern C standards and syntax, while SDCC sticks closely to older C89 rules by default. This is one of the most common friction points when porting code between these two compilers—don't feel bad for hitting it as an intern, it's a classic learning moment!
内容的提问来源于stack exchange,提问作者JMA

