Page 1 of 1

How can I modify C variables in another file?

Posted: Mon May 11, 2015 8:27 am
by Mikumiku747
Hello,
I'm sure this is a common question, but I had a look and couldn't find any obvious answers, so yeah. Anyways, I'm making the input handler for my kernel, and I have an array of characters that I'm storing the input in. Problem is, I need to modify this array from my interrupt handler, which is in a separate C file I've included into the main c file. However, I can't seem to edit the value from the interrupt handler, its having no effect.

Here's a quick example of the code I'd be using:

Code: Select all

//Main.c
#include "interrupts.c"

char *command[2000];
char *original = command;

int main() {
    //stuff
    for (int i = 0; i<2000; i++) {
        command[i] = 0;
    }
    while (*command != 'e');
    printf("command length %i\n", command-original);
}

Code: Select all

//interrupts.c

extern char *command;

void handle_kbd() {
    char kbd = read_keyboard();
    *command = kbd;
    command++;
}
Please try to ignore obvious spelling mistakes, the code is there for example.

Long story short, I'm modifiying the variable in the interrupt handler, but it has no effect. Im confused by this, and my first hunch was that it's 2 seperate varibless, but I used objdump and saw only one symbol called command In the resulting binary. So now I'm out of ideas and have come to you for help. I know my way around C, but i'm not sure why it's not working, And i haven't really worked with the extern keyword before. Also, for some reason, the linker throws a fit if I don't declare the variable in interrupts.c, even though it's getting included by the mainfile.

Does anybody have any ideas, I would really appreciate them :D
Thanks, Mikumiku747

Re: How can I modify C variables in another file?

Posted: Mon May 11, 2015 9:38 am
by iansjack
In main.c you declare command as a char **. In interrupts.c you use it as a char *. That's going to lead to unexpected behaviour.

Re: How can I modify C variables in another file?

Posted: Mon May 11, 2015 10:17 am
by Combuster
What iansjack said, and Volatile

Re: How can I modify C variables in another file?

Posted: Mon May 11, 2015 10:18 pm
by Mikumiku747
AH, it needs to be volatile, I didn't even consider that it might get optimized, but now that I look at it, it makes quite a lot of sense. Also, I typed out the code on my phone, so the double pointer is just a typo, it doesn't have the asterisk in the actual code. Thanks for the lesson, it's exactly what I was looking for. :)