c - 对“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
解决方案
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 查看输出文件的扩展名。您必须使用单独的选项。
推荐阅读
- sql-server - 在 rdlc 报告 vb.net 中传递日期范围
- php - PHP cURL - 带有数据返回的 API Auth Token
- python - LSTM 分类的时间序列数据准备
- javascript - Lambda 上的 Puppeteer Node.js 脚本
- vba - Outlook 自定义表单共享
- laravel - 如何制作可重新排列的对象并为每个用户显示它们
- lua - 我在创作游戏时经常在 Roblox Studio 中听到“鲜肉”这个词
- azure-devops - 在 Azure DevOps 中,当部署到生产环境的构建引用时,孤立的 git 提交/对象是否会保留?
- linux - 是否有可能留在使用 execl 的进程打开的 shell 中,就在名为 _exit 的进程之前?
- visual-studio-code - In VSCode snippets how do you use transform to lowercase just the first letter of a value?