它不起作用的原因是__asm是一个关键字,就像int是一个关键字一样,它不能单独出现,必须遵循正确的语法。以下面这段代码为例:
int main()
{
int // here's a comment, but it's ignored by the compiler
return 0;
}
以下代码将因编译错误而失败,更具体地说,在 VS2012 中您会得到 error C2143: syntax error : missing ';' before 'return'。这是一个明显的错误,因为我们没有结束分号来表示指令的结束;添加分号并编译正常,因为我们没有违反 C(或本例中为 C++)语言的语法:
int main()
{
int // here's a comment, but it's ignored by the compiler
; // white space and comments are ignored by the compiler
return 0;
}
下面的代码也是如此:
int main()
{
__asm ; here's a comment but it's ignored
return 0;
}
除了这里我们得到错误error C2400: inline assembler syntax error in 'opcode'; found 'constant',因为它将__asm关键字之后的所有内容都视为汇编指令,并且注释被正确地忽略了..所以下面的代码可以工作:
int main()
{
__asm ; here's a comment but it's ignored
NOP ; white space and comments are ignored by the compiler
__asm {; here's an __asm 'block'
} // outside of __asm block so only C style comments work
return 0;
}
这就回答了你的第一个问题:Why didn't VS allow me to add an assembly comment?.. 因为它是语法错误。
现在回答你的第二个问题:Is there a different way to add an assembly comment without adding an instruction, including NOP?
直接,不,没有,但间接,是的。值得注意的是,__asm 关键字在您的程序中被编译为内联程序集,因此 cmets 将从已编译的程序集中删除,就好像它是标准 C/C++ 注释一样,因此尝试在您的程序集中“强制”注释不需要通过该方法,相反,您可以使用/FAs 编译器标志,它将生成与源代码混合的程序集(机器代码),例如:
给出以下(非常简单的)代码:
int main()
{
// here's a normal comment
__asm { ; here's an asm comment and empty block
} // here's another normal comment
return 0;
}
使用/FAs 编译器标志编译时,生成的file.asm 具有以下输出:
; Listing generated by Microsoft (R) Optimizing Compiler Version 18.00.31101.0
TITLE C:\test\file.cpp
.686P
.XMM
include listing.inc
.model flat
INCLUDELIB LIBCMT
INCLUDELIB OLDNAMES
PUBLIC _main
; Function compile flags: /Odtp
; File c:\test\file.cpp
_TEXT SEGMENT
_main PROC
; 2 : {
push ebp
mov ebp, esp
; 3 : // here's a normal comment
; 4 : __asm { ; here's an asm comment and empty block
; 5 : } // here's another normal comment
; 6 : return 0;
xor eax, eax
; 7 : }
pop ebp
ret 0
_main ENDP
_TEXT ENDS
END
注意它是如何包含源和 cmets 的。如果这段代码做得更多,你会看到更多的程序集和与之相关的源代码。
如果您想将 cmets 放入内联程序集本身,则可以使用普通 C/C++ 样式 cmets 以及 __asm 块本身内的程序集 cmets:
int main()
{
// here's a C comment
__asm { ; here's an asm comment
// some other comments
NOP ; asm type comment
NOP // C style comment
} // here's another comment
return 0;
}
希望能有所帮助。
编辑:
应该注意以下代码也可以正确编译,但我不是 100% 确定原因:
int main()
{
__asm
__asm ; comment
// also just doing it on a single line works too: __asm __asm
return 0;
}
使用单个 __asm ; comment 编译此代码会产生编译错误,但两者都可以正常编译;在上面的代码中添加指令并检查.asm 输出表明第二个__asm 被其前面的任何其他汇编命令忽略。所以我不能 100% 确定这是一个解析错误还是 __asm 关键字语法的一部分,因为没有关于这种行为的文档。