title: Simple assembly example : set inputs and get output - right syntax
body: <p>I try to do a simple example to insert, into a C code, a piece of Sparc assembly 32 bits; this little code performs an incrementation on the variable  "sum".</p>
  
  <p>The code is :</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;sys/time.h&gt;
  #include &lt;unistd.h&gt;
  
  int n;
  int sum;
  
  int main ()
  {
    n = 100;
    sum = 0;
  
    struct timeval tv1, tv2;
    long long diff;
  
    gettimeofday (&amp;tv1, NULL);
  
    asm volatile ("set sum, %g1\n\t" \
                  "set n, %g3\n" \
                  "loop:\n\t" \
                  "add %g1, 1, %g2\n\t" \
                  "sub %g3, 1, %g4\n\t" \
                  "bne loop\n\t" \
                  "nop\n\t" \
                  : "=r" (sum)
                  : "r" (n)
                  );
  
    gettimeofday (&amp;tv2, NULL);
  
    diff = (tv2.tv_sec - tv1.tv_sec) * 1000000L + (tv2.tv_usec - tv1.tv_usec);
    printf ("Elapsed time = %d usec\n", diff);
  
    printf ("Sum = %d\n", sum);
  
    return 0;
  
  }
  </code></pre>
  
  <p>Unfortunately, compilation with gcc4.1.2 produces the following errors :</p>
  
  <pre><code>loop_dev_for-assembly_code.c: In function #main#:
  loop_dev_for-assembly_code.c:18: error: invalid 'asm': invalid operand output code
  loop_dev_for-assembly_code.c:18: error: invalid 'asm': operand number out of range
  loop_dev_for-assembly_code.c:18: error: invalid 'asm': invalid operand output code
  loop_dev_for-assembly_code.c:18: error: invalid 'asm': operand number out of range
  loop_dev_for-assembly_code.c:18: error: invalid 'asm': operand number out of range
  loop_dev_for-assembly_code.c:18: error: invalid 'asm': operand number out of range
  </code></pre>
  
  <p>It seems the line 18 corresponds to "<code>asm volatile ("set sum, %g1\n\t" \ ...</code>".</p>
  
  <p>But I don't know how to circumvent these errors. It may come from the variable <code>sum</code> which is set to <code>%g1</code> register.</p>
  
  <p>About the links between variable belonging to C code and variable localted in Assembly code part. I have also seen, for inputs and outputs parameters, the syntax <code>"=g"</code> (output paramter ??), <code>"g"</code> (input parameter) : I think that it corresponds to different registers between the 2 syntax.</p>
  
  <p>if someone could give to me some clues to understand this link and debug my little code which does a simple loop to increment <code>variable sum</code>. </p>
  
  <p>Thanks for your help, regards.</p>