Reputation: 1
So in short, I have two .c files and a shared.h header file in the same directory.
This is shared.h:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <string.h>
#include <fcntl.h>
#include <signal.h>
#include <errno.h>
// declaring the number to factor and the the variable
factor as shared gloval variables
extern int n;
extern int factor;
This is pfact.c:
#include "shared.h"
int n;
int factor = 0;
// start main
int main(int argc, char **argv) {
// fork
// if child, exec to child
return 0;
}
This is child.c:
#include "shared.h"
int main(){
int m=0, k;
int status, child_exit_status;
pid_t pid;
int fd[2]; //every child will create another pipe to write to in addition to the pipe it inherits from its parent to read from
printf("n is %d\n", n);
// goes more code
return 0
}
What am I doing wrong? the global variable n is declared once in pfact.c, "externed" in the header file shared.h and then the header file is included in child.c
Thanks in advance!
Upvotes: 0
Views: 120
Reputation: 11791
You need to link your objects together...
gcc -g -Wall -c child.c
gcc -g -Wall -c pfact.c
gcc -g -Wall -o pgm child.o pfact.o
Re: extern
lines useless: Yes, they aren't needed in pfact.c
; but it is good practice to #include
the header with the declaration anyway, so the compiler can cross-check that everything matches.
Upvotes: 0
Reputation: 1062
Those two lines in child.c are useless, you can remove it
extern int n;
extern int factor;
This could help you understand why:
How do I use extern to share variables between source files?
Child doesn't know n so you can add it in global in child.c but it's certainly not why you are trying to do.
You can't compile two main, you should maybe rethink the way you do your program.
Upvotes: 2