首页 > 解决方案 > 对“stack_init”的未定义引用

问题描述

测试.c

#include <stdio.h>
#include <stdlib.h>
#include "dslib.h"
//#include "stack.c"

int main()
{
    stack myStack;
    char buffer[1024];

    stack_init(&myStack, 6);
    int i;

    for(i = 0; i < myStack.max; i++){
      stack_push(&myStack, (i+1)*2);
    }
    printf("Hello\n");
    return 0;

堆栈.c

#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include "dslib.h"
//#define stack_init main

void stack_init(stack *s, int capacity)
{
  //  struct stack_t *s = (struct stack_t*)malloc(sizeof(struct stack_t));

    s->max = capacity;
    s->count = -1;
    s->data = (int*)malloc(capacity * sizeof(int));
    //return s;
}

int stack_size(stack *s)
{
    return s->count;
}

int stack_pop(stack *s)
{
    if(s->count == 0){
      return -1;
    }
    s->count--;

    int pop = s->data[s->count];
    s->data[s->count] = 0;
    return pop;
}

void stack_push(stack *s, int e)
{
    if(s->count != s->max){
      s->data[s->count] = e;
      s->count++;
    }
}

void stack_deallocate(stack *s)
{
  free(s->data);
}

dslib.h

#ifndef DSLIB_H
#define DSLIB_H

#include <stdio.h>
#include <stdlib.h>

typedef struct stack
{
int count; // the number of integer values currently stored in the stack
int *data; // this pointer will be initialized inside stack_init(). Also, the actual size of
//the allocated memory will be determined by “capacity’ value that is given as one of the
//parameters to stack_init()
int max; // the total number of integer values that can be stored in this stack
}stack;

void stack_init(stack* s, int capacity);
int stack_size(stack *s);
int stack_pop(stack *s);
void stack_push(stack *s, int e);
void stack_deallocate(stack *s);

#endif

生成文件

cc=gcc

file: test.o stack.o file.o
    gcc -o file test.o stack.o file.o

file.o: file.c
    gcc -o file.o file.c

test.o: test.c
    gcc -o test.o test.c

stack.o: stack.c
    gcc -o stack.o stack.c

当我执行make时,它会发出这个:

gcc -o test.o test.c
/tmp/ccJMitGw.o: In function `main':
test.c:(.text+0x2a): undefined reference to `stack_init'
test.c:(.text+0x53): undefined reference to `stack_push'
collect2: error: ld returned 1 exit status
Makefile:10: recipe for target 'test.o' failed
make: *** [test.o] Error 1

标签: c

解决方案


gcc -o test.o test.c

这会尝试编译并链接test.c到具有不寻常名称的可执行文件test.o中。这显然失败了,因为test.c它本身并不是一个完整的程序。

要将源文件编译并组装成目标文件,您需要使用以下-c选项:

gcc -c -o test.o test.c

您的 makefile 的其他编译规则也是如此。

这里 gcc 的行为略有不一致:它查看输入文件的扩展名以帮助它决定要做什么(.c文件被编译为 C,.cpp文件被编译为 C++,.s文件只被组装,等等)但它没有t 查看输出文件的扩展名。您必须使用单独的选项。


推荐阅读