c++中的静态库不起作用

Static lib in c++ not working

本文关键字:不起作用 静态 c++      更新时间:2023-10-16

我有文件夹ClientServer。在这个文件夹中,我有另外两个文件夹,DatabaseServer。在Server文件夹中,我有使用"database.h"answers"新闻组.h"的类。这些文件在Database文件夹中。我用这个make文件创建了一个库。我将libfile移动到ClientServer文件夹。然后我试着在Server文件夹中调用Make;我得到错误。

Makefile:47: ans.d: No such file or directory
Makefile:47: com.d: No such file or directory
Makefile:47: myserver.d: No such file or directory
In file included from myserver.cc:11:0:
ans.h:4:23: fatal error: newsGroup.h: No such file or directory
#include "newsGroup.h"
                   ^
compilation terminated.

#
# Makefile to make the file libclientserver.a, containing
# connection.o and server.o
#
# Define the compiler. g++ can be
# changed to clang++.
CXX = g++
CC  = g++
# Define preprocessor, compiler, and linker flags. Uncomment the # lines
# if you use clang++ and wish to use libc++ instead of libstdc++.
CXXFLAGS =  -g -O2 -Wall -W -pedantic-errors
CXXFLAGS += -Wmissing-braces -Wparentheses -Wold-style-cast 
CXXFLAGS += -std=c++11 
#CPPFLAGS =  -stdlib=libc++
#CXXFLAGS += -stdlib=libc++
#LDFLAGS += -stdlib=libc++
all: libdatabase.a
# Create the library; ranlib is for Darwin and maybe other systems.
# Doesn't seem to do any damage on other systems.
libdatabase.a: Database.o newsGroup.o
    ar rv libdatabase.a Database.o newsGroup.o 
    ranlib libdatabase.a
# Phony targets
.PHONY: all clean
# Standard clean
clean:
    rm -f *.o libclientserver.a
# Generate dependencies in *.d files
%.d: %.cc
    @set -e; rm -f $@; 
         $(CPP) -MM $(CPPFLAGS) $< > $@.$$$$; 
         sed 's,($*).o[ :]*,1.o $@ : ,g' < $@.$$$$ > $@; 
         rm -f $@.$$$$
# Include the *.d files
SRC = $(wildcard *.cc)
include $(SRC:.cc=.d)

newsGroup.h在目录结构中的位置?.cpp文件看到它在同一个目录吗??否则,使用-I选项,告诉编译器该文件可以在哪个目录中找到。

-I <path_to>/Database添加到CXXFLAGS中,其中<path_to>可能是用于运行编译器的工作目录的完整路径或相对路径:

CXXFLAGS += -I<path_to>/Database
另一个选择是在#include语句中指定一个相对路径,例如在ans.h中写
#include "Database/newsGroup.h"

-I选项只指向<path_to>/
由于.d文件将在生成时接收这些路径,并且在此指定依赖项,因此还应该从make的工作目录中相对地查看.h依赖项。

实际上,标准库只保存了"函数体"。

您仍然需要声明函数的原型(包括.h文件),并使编译器可以访问它。

所以,在你的情况下,让你的编译器可以访问newsgroup.h(在这种情况下,把它放在与ans.h文件相同的文件夹中),它应该解决问题。