获取错误未定义参考

时间:2016-06-11 05:52:06

标签: c linker

diceroll.c

/*diceroll.c -- dice roll simulation */  
#include "diceroll.h"  
#include <stdio.h>  
#include <stdlib.h> //for library function rand()  

int roll_count = 0; //external linkage  

static int rollem(int sides) /*private to this file */  
{  
    int roll;  

    roll = rand() % sides + 1;  
    ++roll_count;  

    return roll;  
}  
int roll_n_dice(int dice, int sides){  
    int d;  
    int total =  0;  
    if(sides < 2){  
        printf("Need at least 2 sides.\n");  
        return -2;  
    }  
    if(dice < 1){  
        printf("Need at least 1 dice.\n");  
        return -1;  
    }  
    for(d = 0; d < dice; d++){  
    total += rollem(sides);  
    }  
    return total;  
}  

标头文件

//diceroll.h  
extern int roll_count;  
extern int roll_n_dice(int dice, int sides);  

主程序

/*manydice.c -- multiple dice rolls     */  
/*compile with diceroll.c           */  
#include <stdio.h>  
#include <stdlib.h> //for library funcion srand()  
#include <time.h>   //for time()  
#include "diceroll.h"   //for roll_n_dice and roll_count  

int main(void){  
    int dice, roll;  
    int sides;  

    srand((unsigned int ) time(0)); /*randomized seed*/
    printf("Enter the number of sides per die, 0  to stop.\n");
    while(scanf("%d", &sides) == 1 && sides > 0){
        printf("How many dice ?\n");
        scanf("%d", &dice);

        roll = roll_n_dice(dice, sides);
        printf("You have rolled a %d using %d %d-sided dice.\n", roll,           dice, sides);  
        printf("How many sides ? Enter 0 to stop.\n");
}  
printf("The rollem() funcion was called %d times.\n", roll_count);               //used extern variable
printf("Good Fortune To You!!!\n");  

return 0;  
}

这是我用

编译它
gcc manydice.c diceroll.c

但它继续说对roll_count和roll_n_dice

的未定义引用

即使我将两者都联系起来,如何修复未定义的引用 源文件。

我也用过2次:

gcc sourcefile.c -o sourcefile.o -c 

对于manydice和diceroll并使用目标代码编译它,但我仍然得到相同的错误。

即:

gcc manydice.c -o manydice.o -c
gcc diceroll.c -o diceroll.o -c
gcc -o myresult manydice.o diceroll.o  

0 个答案:

没有答案