C ++使用文件夹结构时的未定义符号

时间:2014-07-01 07:38:46

标签: c++ compilation makefile undefined-symbol

我目前正在尝试了解OpenGL并找到了this教程。我已经达到了一个我想从我所学到的东西中取得一些成果的地步所以我已经厌倦了设置一个带有(某种程度上)自制Makefile的小项目文件夹。该项目的结构如下:

project_root:
 -- Makefile
 -- src/
       main.cpp
       imageloader.cpp
 -- obj/
       main.o (no compiletime error)
       imageloader.o (no compiletime error)
 -- include/
       imageloader.h
 -- textures/
       some texture files

Makefile:

CC = g++

SRC_DIR = ./src
OBJ_DIR = ./obj
INC_DIR = ./include

INCLUDE_PATHS = -I/usr/local/include -I/opt/X11/include -I$(INC_DIR)
LIBRARY_PATHS = -L/usr/local/lib -I/opt/X11/lib
LINKER_FLAGS = -framework OpenGL -lGLUT
COMPILER_FLAGS = -w

SRC_FILES = main.cpp imageloader.cpp
HEADER_FILES = imageloader.h

HEADERS = $(HEADER_FILES:%.h=$(INC_DIR)/%.h)
SRC = $(SRC_FILES:%.cpp=$(SRC_DIR)/%.cpp)

OBJS = $(SRC_FILES:%.cpp=$(OBJ_DIR)/%.o)

EXEC = main

$(OBJ_DIR)/%.o: $(SRC)
        $(CC) $(INCLUDE_PATHS) $(LIBRARY_PATHS) $(COMPILER_FLAGS) -c -o $@ $<

all: $(OBJS) $(HEADERS)
        $(CC) $(OBJS) $(INCLUDE_PATHS) $(LIBRARY_PATHS) $(COMPILER_FLAGS)         $(LINKER_FLAGS) -o $(EXEC)

run:
    ./main

print:
        @echo "C++ objcet files: "$(OBJS)
        @echo "C++ source files: "$(SRC)
        @echo "C++ header files: "$(HEADERS)

clean:
       rm -fv $(EXEC)
       rm -fv $(OBJS)

当我尝试编译它时,我得到以下输出:

g++ -I/usr/local/include -I/opt/X11/include -I./include -L/usr/local/lib -I/opt/X11/lib -w -c -o obj/main.o src/main.cpp
g++ -I/usr/local/include -I/opt/X11/include -I./include -L/usr/local/lib -I/opt/X11/lib -w -c -o obj/imageloader.o src/main.cpp
g++ ./obj/main.o ./obj/imageloader.o -I/usr/local/include -I/opt/X11/include -I./include -L/usr/local/lib -I/opt/X11/lib -w -framework OpenGL -lGLUT -o main
Undefined symbols for architecture x86_64:
  "loadBMP(char const*)", referenced from:
      initRendering()     in main.o
      initRendering()     in imageloader.o
  "Image::~Image()", referenced from:
      initRendering()     in main.o
      initRendering()     in imageloader.o
ld: symbol(s) not found for architecture x86_64
collect2: ld returned 1 exit status
make: *** [all] Error 1

困扰我的是代码是从教程站点获取的,没有任何修改,当我在同一个文件夹(同一个地方的所有.cpp和.h文件)中编译它时,它编译得很好。我有一种感觉,我犯了一个明显的错误,但我似乎无法找出导致错误的原因?

有人可以指出为什么不编译吗?

提前致谢:)

1 个答案:

答案 0 :(得分:1)

你正在编译main.cpp两次:

g++ -I/usr/local/include -I/opt/X11/include -I./include -L/usr/local/lib -I/opt/X11/lib -w -c -o obj/main.o src/main.cpp <--- main.cpp
g++ -I/usr/local/include -I/opt/X11/include -I./include -L/usr/local/lib -I/opt/X11/lib -w -c -o obj/imageloader.o src/main.cpp <--- main.cpp, instead imageloader.cpp