1

I'm confused how to use #define, or if this is even what I want to be using.

I have a header file:

#define var     3;

int foo();

...(etc)

As well as two similarly structured files outside of it:

#include "header.h"

int main(int argc, char **argv){

    printf("%i", var);
}

Am I wrong in thinking that I can use the var from the header in C files which include the header?

This is actually a part of homework, and I'm not permitted to change the header file. If I can't use it like this, is there some way to use the variable outside the file other than an accessor function?

3
  • 1
    #define var 3; is horrible, horrible C (especially that semicolon on the end). If this is the code you were provided, you should complain to the instructor... Commented Mar 3, 2014 at 23:21
  • 1
    #define var 3; Omit the ';' Commented Mar 3, 2014 at 23:21
  • But your header file is strange. The ; after 3 should not be there. Commented Mar 3, 2014 at 23:22

2 Answers 2

3

Just don't put a semicolon to the end of your defined value. Instead of

#define var 3;

use

#define var 3

With your define the print statement is expanded to the following by the preprocessor:

printf("%i", 3;);

...that is invalid code. The preprocessor doesn't really respect the rules of the C/C++ language, it's rather a barbar textual substitution tool, maybe a bit smarter than that but much more dumber than the C language itself...

If you are not allowed the change the header then you can still say

int my_variable = var

And you can even put any number of semicolons after the previous statement if you like that more.

Sign up to request clarification or add additional context in comments.

Comments

1

The header file needs to be properly defined:

#ifndef HEADER_FILE
#define HEADER_FILE

#define var 3 // <-- no semi

#endif

Now depending on how you defined var, you should be able to do:

#include "header.h"

int main(int argc, char **argv){

    printf("%i", var);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.