What are the best strategies for finding that missing semicolon that's causing the error? Are there automated tools that might help.
I'm currently using Visual Studio 2开发者_如何学运维008, but general strategies for any environment would be interesting and more broadly useful.
Background:
Presently I have a particularly elusive missing semicolon (or brace) in a C++ program that is causing a C2143 error. My header file dependencies are fairly straightforward, but still I can't seem to find the problem. Rather than post my code and play Where's Wally (or Waldo, depending on where you're from) I thought it would be more useful to get some good strategies that can be applied in this and similar situations.As a side-question: the C2143 error is showing up in the first line of the first method declaration (i.e. the method's return type) in a .cpp file that includes only its associated .h file. Would anything other than semicolons or braces lead to this behaviour?
Did you forget the semicolon after the class definition in the header? That's a fairly common cause of errors on the first method in the cpp file. I don't think there's a general magic "find the missing semicolon" tool; VS tries to make an educated guess, but if it's off it's because the code you wrote is somewhat legal without it, even if it's not what you intended
Start from the line that the compiler told you the error is on and look at the code immediately preceding that line.
It's unlikely to be a missing semicolon, except (as @Michael suggested) from the end of a class. Generally a missing semicolon causes an error within a line or two.
If it's a scope brace then it's usually not too far away, although sometimes they can be a long way off..
Backtrack from the error line (go backwards up the code, and then backwards through each include from the bottom one), checking the braces. Chances are it's at the start of your cpp file just prior to the site of the error, or the end of the last include, so that's the best place to start.
You can use various techniques:
Just read the code. If you follow a clean symmetrical coding style a missing brace will often slap you in the face. (You can use Edit->Advanced->Format Document to tidy up code if it is in an inconsistent style).
Place the cursor on each end of scope } and press ctrl+} to take the cursor to the matching brace. This will either do nothing, in which case there is no match, or will jump to the match and you can check that it is the correct brace.
If you have a lot of code to consider, just comment a lot of it out with #if FALSE. You'll get different compiler errors, but if the original error stays you know it's not caused by the commented code, and you can move on to the next include/class/block.
The worst case scenario is that it's some code in a macro. If you have added/edited/used any macros in the last day, then check them first.
精彩评论