早上好,我是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()
a static
函数,使其定义只在这个翻译单元中可见,而对链接器不可见。删除关键字 static
在这里,也在 server.h
如果你已经声明了函数 static
那里。
A namespace
不是 class
或 struct
. 令人困惑的是。
namespace server {
static char* get_domain() {
return getenv("SERVER_NAME");
}
}
server::get_domain()
是一个 静态 在该命名空间中的函数。但是
struct server {
static char* get_domain() {
return getenv("SERVER_NAME");
}
};
它是 全球性 中的函数,链接器可以看到。