Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Скачиваний:
50
Добавлен:
14.04.2015
Размер:
1.37 Mб
Скачать

Keil Software — Cx51 Compiler User’s Guide

379

 

 

Function Pointers

Function pointers are one of the most difficult aspects of C to understand and to properly utilize. Most problems involving function pointers are caused by improper declaration of the function pointer, improper assignment, and improper dereferencing.

The following brief example demonstrates how to declare a function pointer (f), how to assign function addresses to it, and how to call the functions through the pointer. The printf routine is used for example purposes when running DS51 to simulate program execution.

#pragma code symbols debug oe

 

 

#include <reg51.h>

/* special function register declarations */

 

#include <stdio.h>

/* prototype declarations for I/O functions */

 

void func1(int d) {

/* function #1 */

 

printf("In FUNC1(%d)\n", d);

 

 

}

 

 

 

 

void func2(int i) {

/* function #2 */

 

printf("In FUNC2(%d)\n", i);

 

 

}

 

 

 

 

void main(void) {

 

 

 

void (*f)(int i);

/* Declaration of a function pointer */

 

 

 

/* that takes one integer arguments */

 

 

 

/* and returns nothing */

 

SCON

= 0x50;

/* SCON: mode 1, 8-bit UART, enable rcvr */

 

TMOD |= 0x20;

/* TMOD: timer 1, mode 2, 8-bit reload */

F

TH1

= 0xf3;

/* TH1:

reload value for 2400 baud */

 

TR1

= 1;

/* TR1:

timer 1 run */

 

TI

= 1;

/* TI:

set TI to send first char of UART */

 

while( 1 ) {

 

 

 

f = (void *)func1;

/* f points to function #1 */

 

f(1);

 

 

 

f = (void *)func2;

/* f points to function #2 */

 

f(2);

 

 

 

}

}

NOTE

Because of the limited stack space of the 8051, the linker overlays function variables and arguments in memory. When you use a function pointer, the linker cannot correctly create a call tree for your program. For this reason, you may have to correct the call tree for the data overlaying. Use the OVERLAY directive with the linker to do this. Refer to the Ax51 Macro Assembler User’s Guide for more information.

380

Appendix F. Hints, Tips, and Techniques

 

 

F

Keil Software — Cx51 Compiler User’s Guide

381

 

 

F

Соседние файлы в папке HLP