Hi StackOverflow wizards:
I have the following three simple C files:
// File 1
#include "mainPgm.h"
void file1() {
printf("N1 is now %d.\n", n1);
}
// File 2
#include "mainPgm.h"
void file2() {
printf("N2 is now %d.\n", n2);
}
// File 3
#include "mainPgm.h"
void file3() {
printf("N3 is now %d.\n", n3);
}
And, of course a main program:
#include <stdio.h>
#include <stdlib.h>
#include "mainPgm.h"
int main() {
int n1 = 65536,
n2 = 256,
n3 = 16;
file1();
file2();
file3();
}
Finally, a header file:
#include<stdio.h>
void file1(), file2(), file3();
extern int n1, n2, n3;
All these are compiled with a simple gcc command:
gcc -std=gnu99 -O2 -o jj -Wunused file1.c file2.c file3.c mainPgm.c
This results in the following errors:
mainPgm.c: In function ‘main’:
mainPgm.c:8:7: warning: unused variable ‘n3’ [-Wunused-variable]
mainPgm.c:7:7: warning: unused variable ‘n2’ [-Wunused-variable]
mainPgm.c:6:7: warning: unused variable ‘n1’ [-Wunused-variable]
/tmp/ccVQjFHY.o: In function `file1':
file1.c:(.text+0x2): undefined reference to `n1'
/tmp/ccZqyI0n.o: In function `file2':
file2.c:(.text+0x2): undefined reference to `n2'
/tmp/ccbpJOpN.o: In function `file3':
file3.c:(.text+0x2): undefined reference to `n3'
collect2: error: ld returned 1 exit status
I thought that defining n1, n2, and n3 in mainPgm.h would serve to declare the variables, and their definition in mainPgm.c would define them. No so! Where did I go wrong?
TIA!