繁体   English   中英

如何为多个目录中的多个文件创建Makefile?

[英]How to create Makefile for multiple files in multiple directories?

早上好,我是 c++ 的新手,我正在尝试将我的简单代码编译为可执行形式。 我将解释项目的结构。

- main.cpp
- /utility/server.h
- /utility/server.cpp

我附上文件来源以获取完整信息。 main.cpp

#include <iostream>
#include "utility/server.h"

using namespace std;
using namespace server;

int main() {
    std::cout << "Content-type:text/html\r\n\r\n";
    std::cout << "Your server name is: " << server::get_domain() << '\n';
    return 0;
}

server.cpp

#include <cstdlib>
#include "server.h"

namespace server {
    static char* get_domain() {
        return getenv("SERVER_NAME");
    }
}

在我的 Makefile 中,我添加了评论以了解我想要做什么。

#
# 'make'        build executable file 
# 'make clean'  removes all .o and executable files
#

# define the C compiler to use
CC = g++

# define any compile-time flags
CFLAGS = -Wall -g

# define any directories containing header files other than /usr/include
INCLUDES = -I../utility

# define the C++ source files
SRCS = main.cpp utility/server.cpp

# define the C++ object files 
OBJS = $(SRCS:.cpp=.o)

# define the executable file 
MAIN = executable.cgi

#
# The following part of the makefile is generic
#

.PHONY: depend clean

all:    $(MAIN)

$(MAIN): $(OBJS) 
        $(CC) $(CFLAGS) $(INCLUDES) -o $(MAIN) $(OBJS)

# this is a suffix replacement rule for building .o's from .cpp's
.c.o:
        $(CC) $(CFLAGS) $(INCLUDES) -cpp $<  -o $@

clean:
        $(RM) *.o *~ $(MAIN)

depend: $(SRCS)
        makedepend $(INCLUDES) $^

最后编译错误

g++ -Wall -g -I../utility -o executable.cgi main.o utility/server.o
Undefined symbols for architecture x86_64:
  "server::get_domain()", referenced from:
      _main in main.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make: *** [executable.cgi] Error 1

从错误消息中我了解到utility文件夹有问题,但我不知道如何解决它。 谢谢您的帮助:)

server.cpp中,这里:

namespace server {
    static char* get_domain() {
        return getenv("SERVER_NAME");
    }
}

您已将char* server::get_domain() static function,使其定义仅在此翻译单元中可见,而对 Z3175B426046787EECE7377387340B982 不可见。 如果您在此处声明了server.h static ,则在此处删除关键字static以及 server.h 中的关键字。

namespace不是classstruct 令人困惑的是,

namespace server {
    static char* get_domain() {
        return getenv("SERVER_NAME");
    }
}

server::get_domain()是该命名空间中的static function 。

struct server {
    static char* get_domain() {
        return getenv("SERVER_NAME");
    }
};

它是一个全局function 在 class 中,linker 可以看到。

暂无
暂无

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

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