2014-03-14 33 views
0

簡而言之,我在同一目錄中有兩個.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中

在此先感謝!

+0

你不需要''extern int n;'等在child.c中,因爲這些聲明在'shared.h'中。確保你實際上將'child.c'和'pfact.c'對象鏈接到你的可執行文件中?刪除了 –

+0

。仍然會遇到同樣的問題:在執行時未定義的引用n:gcc -o child child.c – user3417884

+1

您需要在該行添加'pfact.c',編譯器不會奇蹟般地知道'pfact.c'是你的東西想要投入'孩子' –

回答

2

這兩行中child.c是沒用的,你可以將其刪除

extern int n; 
extern int factor; 

這可以幫助你理解爲什麼:

How do I use extern to share variables between source files?

兒童不知道N.這樣你就可以將它添加到全局的child.c中,但這當然不是你嘗試去做的原因。

你不能編譯兩個主文件,你應該重新考慮你的程序執行方式。

+0

已刪除。仍然有同樣的問題。 – user3417884

0

您需要將對象鏈接在一起......

gcc -g -Wall -c child.c 
gcc -g -Wall -c pfact.c 
gcc -g -Wall -o pgm child.o pfact.o 

回覆:extern線沒用:是的,它們不需要在pfact.c;但是,無論如何,最好使用#include標頭,因此編譯器可以交叉檢查一切是否匹配。