我正在尝试制作一个Makefile,但不太了解它是如何工作的,因此无法真正调试它,并在其中添加适当的内容。
我总共有三个文件。我的“主”文件:
valid_board.cpp
然后我有一个.h和.cpp文件,它们定义了一个类:
xword_puzzle.h
xword_puzzle.cpp
在xword_puzzle.cpp中我写了#include "xword_puzzle.h"
,在xword_puzzle.h中我写了#pragma once
,在valid_board.cpp中我写了#include "xword_puzzle.h"
。尽管如此,当我运行Makefile时,似乎还不能正确包含我在xword_puzzle文件中定义的类。
我将其作为仅编译主文件的makefile。
# the compiler: gcc for C program, define as clang++ for C++
CXX=clang++
# compiler flags:
# -g adds debugging information to the executable file
# -Wall turns on most, but not all, compiler warnings
CXXFLAGS=-g -std=c++11 -Werror -D_GLIBCXX_DEBUG
# the build target executable:
TARGET = valid_board
all: $(TARGET)
$(TARGET): $(TARGET).cpp
$(CXX) $(CXXFLAGS) -o $(TARGET) $(TARGET).cpp
clean:
$(RM) $(TARGET)
错误示例:在xword_puzzle.cpp中,我定义了类
Puzzle::Puzzle(char** xword, int rows, int cols) { ...
但随后在* valid_board.cpp *中,我尝试输入
Puzzle* asdf_puz = new Puzzle(puzzle, 15, 15);
并出现以下错误:
Undefined symbols for architecture x86_64:
"Puzzle::Puzzle(char**, int, int)", referenced from:
_main in valid_board-c21998.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
应注意,我的xword_puzzle.h当前包含
class Puzzle {
public:
Puzzle(char** xword, int rows, int cols);
private:
vector<string> accrosses;
vector<string> downs;
};
并且当我删除public:
时,错误变为
valid_board.cpp:54:28: error: calling a private constructor of class 'Puzzle'
Puzzle* asdf_puz = new Puzzle(puzzle, 15, 15);
^
./xword_puzzle.h:15:3: note: implicitly declared private here
Puzzle(char** xword, int rows, int cols);\
^
这使我相信错误可能在其他地方。
您收到的错误Undefined symbols for architecture
表示linker
-一个从多个obj文件“汇编”可执行文件的程序-找不到Puzzle::Puzzle(char**, int, int)
的“实现”,但此实现是必需的。不是您在xword_puzzle.cpp
中有实现,但没有tell
链接器来使用它:
$(CXX) $(CXXFLAGS) -o $(TARGET) $(TARGET).cpp
此行将被解释为:
clang++ -g -std=c++11 -Werror -D_GLIBCXX_DEBUG -o valid_board valid_board.cpp
valid_board.cpp
编译“ valid_board”。 我建议您检查http://www.cs.colby.edu/maxwell/courses/tutorials/maketutor/,因为它提供了一个与您的用例相近的示例:
CXX=clang++
# compiler flags:
# -g adds debugging information to the executable file
# -Wall turns on most, but not all, compiler warnings
CXXFLAGS=-g -std=c++11 -Werror -D_GLIBCXX_DEBUG
# the build target executable:
TARGET = valid_board
DEPS = xword_puzzle.h
OBJ = valid_board.o xword_puzzle.o
%.o: %.c $(DEPS)
$(CC) -c -o $@ $< $(CFLAGS)
$(TARGET): $(OBJ)
$(CXX) -o $@ $^ $(CXXFLAGS)