[英]Undefined reference to function that is already defined in my header file
我有三個文件, posl.h
, state.c
和main.c
。 What I plan on doing is adding functions that are used throughout the project in posl.h
, and then I call it to test the function with main.c
, and then make the function in state.c
. 我遇到的問題是,即使我在posl.h
中定義了undefined reference to init_poslState()
,我仍然會收到錯誤
main.c
#include <posl.h>
int main(int argc, char * argv[]) {
pState poslState = init_poslState();
return 0;
}
posl.h
#ifndef POSL_LANGUAGE_H
#define POSL_LANGUAGE_H
#define POSL_MAJOR_VERSION 1
#define POSL_MINOR_VERSION 0
#define POSL_RELEASE_VERSION 0
// State
typedef struct POSL_STATE {
// ...
} pState;
pState init_poslState();
void free_poslState(pState poslState);
#endif
state.c
#include "state.h"
#include <posl.h>
pState init_poslState() {
pState newState;
return newState;
}
Makefile
CFLAGS=-g -Wall -Wextra -I./include
CC=gcc $(CFLAGS)
CORE_O_FILES=./src/Core/lexer.o ./src/Core/parser.o ./src/Core/state.o
CLI_O_FILES=
O_FILES=$(CORE_O_FILES)
# Making CLI Tool
posl: $(CLI_O_FILES) libposl.a ./src/CLI/main.c
$(CC) -o posl -L./ -lposl ./src/CLI/main.c $(CLI_O_FILES)
# Making Library
libposl.a: $(O_FILES) ./include/posl.h
ar rcs libposl.a $^
# Core Files
./src/Core/lexer.o: ./src/Core/lexer.c ./src/Core/lexer.h
$(CC) -o $@ -c ./src/Core/lexer.c
./src/Core/parser.o: ./src/Core/parser.c ./src/Core/parser.h
$(CC) -o $@ -c ./src/Core/parser.c
./src/Core/state.o: ./src/Core/state.c ./src/Core/state.h
$(CC) -o $@ -c ./src/Core/state.c
# PHONY List
.PHONY: all
all:
make update-libs
make libposl.a
make posl
make pcc
# Post-Compile Clean
.PHONY: pcc
pcc:
rm -rf ./src/Core/*.o
rm -rf ./src/CLI/*.o
.PHONY: clean
clean:
make pcc
rm -rf ./libposl.a ./posl*
編譯器和(尤其是)linker 選項的順序很重要。 用這個命令...
$(CC) -o posl -L./ -lposl./src/CLI/main.c $(CLI_O_FILES)
... linker 不會嘗試解析來自main.c
中函數的任何 function 引用。 它只會查看命令行上出現在main.c
之后的對象和庫。
因此,將該配方重寫為
$(CC) -o posl -L. ./src/CLI/main.c $(CLI_O_FILES) -lposl
韋爾普,@user17732522 回答了我的問題。 我把-l
標志弄亂了,它不在我的源文件之后。 ~謝謝各位!~
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.