繁体   English   中英

如何使用 Makefile 正确编译带有头文件的 C++?

[英]How do I properly compile C++ with header using Makefile?

我正在尝试使用头文件在 macOS 终端上构建程序。 我已经在我的 cpp 文件中包含了标题。 但我遇到了错误:

错误 :

Undefined symbols for architecture x86_64:
  "_main", referenced from:
     implicit entry/start for main executable
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

这是我尝试运行的文件

#include <iostream>
#include <opencv2/opencv.hpp>
#include "plot.h" //Header File 

using namespace cv;
using namespace std;

int PlotGraph(Mat & data) {

    //converting the Mat to CV_64F
    data.convertTo(data, CV_64F);
    Mat plot_result;

    Ptr<plot::Plot2d> plot = plot::Plot2d::create(data);
    plot->setPlotBackgroundColor(Scalar(50, 50, 50));
    plot->setPlotLineColor(Scalar(50, 50, 255));
    plot->render(plot_result);

    imshow("Graph", plot_result);
    waitKey();

    return 0;
}

我尝试使用-c更改编译器,但仍然遇到相同的错误。 这是我的makefile

生成文件:

BIN_DIR= .
CC = g++
CFLAGS = -std=c++11 $(shell pkg-config --cflags opencv)
LIBS = $(shell pkg-config --libs opencv)

all: $(BIN_DIR)/trial1

$(BIN_DIR)/trial1: trial1.o
    ${CC} -o $(BIN_DIR)/trial1 trial1.o $(LIBS)

trial1.o: trial1.cpp
    ${CC} $(CFLAGS) -c trial1.cpp

clean:
    rm -f *.o
    rm -f $(BIN_DIR)/trial1

allclean:
    rm -f *.o
    rm -f $(BIN_DIR)/trial1
    rm -f Makefile

我尝试了其他简单的程序,如“Hello World”,它编译正确,但不是这个。 有什么建议吗?

假设您在问题中输入的代码是整个trail1.cpp并且从链接器错误来看,您似乎错过了一件非常简单的事情......

int main() {
    return 0;
}

这个函数在每个 c/c++ 程序中都是必需的,它必须被称为main (即你不能将它更改为PlotGraph ,你可以创建一个单独的函数PlotGraphmain()调用,但它不能替代)。 您还有两个主要选项。 作为上述方法的替代方法,您可以执行以下操作:

int main(int argc, const char** argv) {
    return 0;
}

(根据您想要的方便程度和精确程度,您可以自由定义 const 的方式......即您也可以使用char const * const * const argv ,但那是另一回事了)

作为最后的提示,您可能应该备份您的 Makefile,因为它看起来像在您运行make allclean您的 makefile 将消失并且您将无法再次运行make由于最后一行是rm -f Makefile

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM