Slide 14.10: Calling C/C++ functions (cont.)
Slide 15.1: Multiplication and division instructions
Home

Calling C/C++ Functions (Cont.)


Code Example—Finding all Factors (Cont.)

 factors.asm 
Title Find all factors (factors.asm)
; An assembly program calls external C/C++ functions.

INCLUDE Irvine32.inc

askForInteger PROTO C
showInt PROTO C, value:SDWORD, outWidth:DWORD

OUT_WIDTH = 8

.data
      save    DWORD ?
.code

;--------------------------------------------------------------
;  Inputs an integer n and displays all factors of the integer.
;--------------------------------------------------------------

DisplayFactors PROC C
    INVOKE askForInteger                  ; call C++ function
    mov    save, eax
    cmp    eax, 0
       
mov ecx, eax L1: mov eax, save ; EAX = input cdq ; dividend = EDX:EAX idiv ecx ; divisor = ECX .IF ( edx == 0 ) ; remainder == 0 push ecx ; save ECX INVOKE showInt, ecx, OUT_WIDTH ; call C++ function call Crlf pop ecx ; restore ECX .ENDIF loop L1 L2: ret DisplayFactors ENDP END
 main.cpp 
// main.cpp

// Demonstrates function calls between a C++ program
// and an external assembly language module.

#include  <iostream>
#include  <iomanip>
using namespace  std;


extern "C" {
  // external ASM procedures:
  void  DisplayFactors( );

  // local C++ functions:
  int   askForInteger( );
  void  showInt( int value, int width );
}


// program entry point
int  main( ) {
  DisplayFactors( );                    // call ASM procedure
  return( 0 );
}


// Prompt the user for an integer. 
int  askForInteger( ) {
  int  n;
  cout << "Enter a positive integer: ";
  cin  >> n;
  return( n );
}


// Display a signed integer with a specified width.
void  showInt( int value, int width ) {
  cout << setw( width ) << value;
}