how can I point to the start of a function in C?
I am writing a program for my class that in a VERY simplified way simulates the way an 开发者_StackOverflow中文版operating system would handle an interrupt.
In C, I have an array INTERRUPT_TABLE[]
that I have declared with:
typedef void (*FN_TYPE)();
extern FN_TYPE INTERRUPT_TABLE[];
I want to set it so that each position in the array points to the beginning of a different function that is contained elsewhere in my program - for example, INTERRUPT_TABLE[0]
should point to the beginning of the function handle_trap()
.
I thought that I could simply say: INTERRUPT_TABLE[0] = handle_trap;
but that is not working. I get a compiler error that says "kernel.c:134: error: subscripted value is neither array nor pointer". Does anyone know what I am doing wrong?
Thanks for the help.
edit: figured out! I had my INTERRUPT_TABLE above the functions I was attempting to call, so they were being automatically declared as ints
Define "not working". That should work. I suspect we're missing some context. Are you tryingto initialize INTERRUPT_TABLE by saying INTERRUPT_TABLE[0] = handle_trap;
somewhere at the top level? That particular syntax won't work there, but will work in a function body. Alternatively you can use initializer syntax:
FN_TYPE INTERRUPT_TABLE[] = { handle_trap, ... };
To elaborate on Logan's answer:
Only (function and object) declarations can appear in the "external" or file context.
While FN_TYPE INTERRUPT_TABLE[] = { handle_trap, ... };
is a definition with initialization, the following has one definition and one assignment operation:
FN_TYPE INTERRUPT_TABLE[];
INTERRUPT_TABLE[0] = handle_trap;
This assignment can't appear at the top level and is interpreted as a redefinition of INTERRUPT_TABLE
.
However, this doesn't match up with the error message you got back. For what it's worth, this simple program compiles successfully:
typedef void (*FN_TYPE) ();
extern FN_TYPE INTERRUPT_TABLE[];
void handle_trap() {
}
int main() {
INTERRUPT_TABLE[0] = handle_trap;
}
When you say elsewhere, I assume it is not in the same file. So you either need a header file that declares handler_trap() or you must declare it manually in your C file before using it:
extern void handler_trap();
Otherwise the compiler has no idea that handler_trap() is a function, which value it returns or which parameters it expects.
精彩评论