簡而言之,我在同一目錄中有兩個.c文件和一個shared.h頭文件。獲取正確定義的全局變量的未定義引用
這是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;
這是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;
}
這是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
}
瓦時我在做錯嗎?全局變量n在pfact.c中聲明一次,在頭文件shared.h中「externed」,然後頭文件包含在child.c中
在此先感謝!
你不需要''extern int n;'等在child.c中,因爲這些聲明在'shared.h'中。確保你實際上將'child.c'和'pfact.c'對象鏈接到你的可執行文件中?刪除了 –
。仍然會遇到同樣的問題:在執行時未定義的引用n:gcc -o child child.c – user3417884
您需要在該行添加'pfact.c',編譯器不會奇蹟般地知道'pfact.c'是你的東西想要投入'孩子' –