I have an ANSI C program comprising two files. The first file contains the main()
function, and the second file contains other functions that the first file calls. Before the main()
function definition, I've placed the following code:
#define PI 3.14159265358979323846
but the 2nd file didn't see this variable. The first file sees it fine. Then, I placed this same line in the second file (while keeping it in the first file as above), before the function definitions, but still the second file doesn't see it. Things always compile fine, but when tracing the variable PI in gdb, it shows "No symbol "PI" in current context."
How to make PI a global constant viewable across all files compiled in the application?
EDIT / UPDATE:
Based on the response so far, I've created the following file:
myheader.h
#ifndef my_header_stuff
#define my_header_stuff
#define PI 3.1415926535897932384626433832795
#endif
and in the two files I want to see this constant PI, I've included this file as follows:
file1.c
#include <stdio.h>
#include <stdlib.h>
#include "myheader.h"
int main(void) {
etc...
}
and file2.c
#include <stdio.h>
#include <stdlib.h>
#include "myheader.h"
double interesting_function(void) {
etc...
}
Questions:
When I use GDB to debug, b PI
returns (in both files, same result) "No symbol "PI" in current context". However, the math depending on PI is computed correctly. Is there a way to view PI in gdb?
Can I also include the two lines for stdio and stdlib in the myheader.h
file?
Can I also include any function prototypes in the myheader.h
file? If I do, and then let's say I create a file3.c that doesn't require any of these prototypes because it doesn't use those functions, is any harm done?
PI
with the actual pi value.#include
in your header filesA macro isn't a variable, and it won't appear in gdb as a variable. Things are compiling fine because they're working fine; you just have the wrong expectations for gdb.
In general, a macro that's needed in more than one place should be defined in a header file that's included everywhere it's needed; for instance, the macro M_PI
is already defined to be pi in the standard include math.h
.
The other thing that you can do is to have const int PI = 3.14159etcetc;
in one file and extern const int PI;
in all of the others, but this is a pain because it requires the definition of the value to exist in exactly one compilation unit.
I'd declare PI in the header file and include this header file to all source files
You should place function declarations, macros in your header file (and maybe some simple inline functions) Implementation should be placed in .c files
// I edited answer to response to your comment
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With