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 mimics the way an operating system interrupts handling.

In C, I have an array INTERRUPT_TABLE[]that I 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 another function that is contained elsewhere in my program - for example, it INTERRUPT_TABLE[0]should point to the beginning of the function handle_trap().

I thought I could just say: INTERRUPT_TABLE[0] = handle_trap;but that doesn't work. I get a compiler error saying: "kernel.c: 134: error: indexed value is neither an array nor a pointer." Does anyone know what I'm doing wrong?

Thanks for the help.

edit: find out! I had INTERRUPT_TABLE over the functions that I was trying to call, so they were automatically declared as ints

+3
source share
3 answers

Define "not working." That should work. I suspect we are missing some context. Are you trying to initialize INTERRUPT_TABLE by speaking INTERRUPT_TABLE[0] = handle_trap;somewhere at the top level? This syntax will not work there, but will work in the function body. Alternatively, you can use the initialization syntax:

  FN_TYPE INTERRUPT_TABLE[] = { handle_trap, ... };
+4
source

To clarify Logan's answer:

Only declarations (function and object) can be displayed in an "external" or file context.

FN_TYPE INTERRUPT_TABLE[] = { handle_trap, ... }; - , :

FN_TYPE INTERRUPT_TABLE[];
INTERRUPT_TABLE[0] = handle_trap;

INTERRUPT_TABLE.

, . , :

typedef void (*FN_TYPE) ();

extern FN_TYPE INTERRUPT_TABLE[];

void handle_trap() {
}

int main() {
    INTERRUPT_TABLE[0] = handle_trap;
}
+1

When you speak elsewhere, I assume this is not the same file. Thus, you either need a header file declaring handler_trap (), or you must manually declare it in your C file before using it:

extern void handler_trap();

Otherwise, the compiler does not know that handler_trap () is a function whose value is returned or what parameters it expects.

0
source

Source: https://habr.com/ru/post/1795239/


All Articles