关于C中原子操作的问题,求助!

问题描述:

处理器:Intel Xeon E3-1230 v2

操作系统:Win 7 64bit

编译器:GCC



代码如下所示:

Processor: Intel Xeon E3-1230 v2
OS: Win 7 64bit
Compiler: GCC

The code is shown below:

// sample.c
#include <stdio.h>

int atomic_add_int(volatile int * address, int value){
	
	asm volatile ("lock xadd %0, %1" : <-- line 11
		"+r" (value) :
		"+m" (*address) :
		"memory");   // <-- line 14
	
	return value;
}

int atomic_inc_int(int * address){
	
	asm volatile("lock inc %0": : <-- line 21
		"+m" (*address):
		"memory");  // <-- line 23
	
	return (*address);
}

int main(){
	
	
}





当我编译代码(> gcc -c sample.c)时,会出现错误:

sample.c:在函数'atomic_add_int'中:

sample.c:14:3:错误:输入操作数约束包含'+'

sample.c:在函数'atomic_inc_int'中:

sample.c:23:3:错误:输入操作数约束包含'+'

sample.c:21:2:错误:输入操作数约束包含'+'

sample.c:在函数'atomic_add_int'中:

sample.c:11:2:错误:输入操作数约束包含'+'



我写了这本书的代码(多核应用程序编程)告诉我,但为什么会出现这些错误?谁能帮我?谢谢。



When I compile the code(>gcc -c sample.c), the errors occur:
sample.c: In function 'atomic_add_int':
sample.c:14:3: error: input operand constraint contains '+'
sample.c: In function 'atomic_inc_int':
sample.c:23:3: error: input operand constraint contains '+'
sample.c:21:2: error: input operand constraint contains '+'
sample.c: In function 'atomic_add_int':
sample.c:11:2: error: input operand constraint contains '+'

I wrote the code as the book(Multicore Application Programming) tell me to, but why those error occur? Can any one help me? Thanks.

这是因为不同指令集架构的不同汇编程序具有不同的语法。因此,对于内联汇编而言,不同的C ++编译器对于不同的指令集架构也是如此。我不知道你提到的那本书的作者是什么意思,但你在你的例子中显示的语法对我来说看起来很陌生。同时,对于x86,x86-64或IE-64的GCC C ++示例看起来非常熟悉。例如,参见:

http://www.advancedlinuxprogramming .com / alp-folder / alp-ch09-inline-asm.pdf [ ^ ]。



-SA
This is because different assemblers for different instruction-set architectures have different syntax. Consequently, the same goes for different C++ compilers for different instruction-set architectures, when it comes to inline assembly. I don't know what was meant by the author of the book you mention, but the syntax you show in your example looks quite foreign to me. At the same time, GCC C++ example for x86, x86-64 or IE-64 look very familiar. See, for example:
http://www.advancedlinuxprogramming.com/alp-folder/alp-ch09-inline-asm.pdf[^].

—SA


哟必须告诉你正在使用什么编译器。正如谢尔盖所​​说,它取决于汇编程序。
Yo have to tell what compiler you are using. As Sergey tells it depends on the assembler.