ju**********@yahoo.co.in writes:
chellappa wrote: hi Everybody !
decalaring variable in a.h and using that vaaariable in a1.c and
inalization is in main.c it is possible .........pleaase correct that
error
is it Possible? i am trying it gives error!
In file included from main.c:2:
a1.c:3: error: initializer element is not constant
a1.c:4: error: variable-size type declared outside of any function
if possible ,please correct it
[snip]
You haven't declared the variable "a" anywhere. In the "a.h" file
it is decalred as an extern variable. What you can do is to have
another
file "a2.c" where you may declare all the global variables
including "a".
See FAQ no 1.7 to find out the correct way to declare a global
variable.
Correction: he's declared it (as extern), but he hasn't defined it.
He should also pay attention to the error message: "variable-size type
declared outside of any function". A variable-size array can be
declared only inside a function.
If you want (the equivalent of) a global variable-size array, declare
a global pointer and assign a value to it. Note that you can't
actually initialize it with a function call, but you can call a
function to do the assignment. (If you forget to call the function,
you've got problems.)
For example:
==> a.h <==
#ifndef HEADER_A
#define HEADER_A
#include <stddef.h>
extern int *a;
extern size_t a_len;
void init_a(size_t length);
#endif
==> a.c <==
#include "a.h"
int *a; /* definition */
size_t a_len; /* definition */
void init_a(size_t length)
{
a = malloc(length * sizeof *a);
a_len = length;
}
==> main.c <==
#include <stdio.h>
#include <stdlib.h>
#include "a.h"
int main(void)
{
init_a(100);
if (a == NULL) {
fprintf(stderr, "malloc failed\n");
exit(EXIT_FAILURE);
}
printf("a = %p\n", (void*)a);
printf("a_len = %lu\n", (unsigned long)a_len);
/*
* Now we can do stuff with a
*/
return 0;
}
--
Keith Thompson (The_Other_Keith)
ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.