【发布时间】:2020-11-14 12:31:52
【问题描述】:
我使用目标文件(有许多子目录)创建了 C++ 静态库。创建静态库后,创建了一个 C 文件和一个包装文件(我在 C++ 目录下拥有的头文件)。现在我正在尝试通过链接 C++ 静态库来编译 C 文件,它会为头文件提供错误
错误:没有这样的文件或目录。
当我使用-I 选项(-I C++ 头文件位置)编译成功并且能够运行。但我想使用静态库而不包括头文件位置,即只添加静态库本身 C 程序应该编译成功。
以下是出处:
编辑:
我在 libbasic 文件夹下有以下文件:
testdemo.h
#ifndef TESTDEMO_H
#define TESTDEMO_H
#include<iostream>
#include<string>
using namespace std;
class testdemo
{
public:
testdemo();
void CallingTestDemo();
};
#endif // TESTDEMO_H
testdemo.cpp
#include "testdemo.h"
testdemo::testdemo()
{
}
void testdemo::CallingTestDemo()
{
`cout <<" CallingTestDemo!!!!!!\n";
}
testbasic.h
#ifndef LIBBASIC_H
#define LIBBASIC_H
#ifdef __cplusplus
#include<iostream>
#include<testdemo.h>
using namespace std;
class Libbasic
{
public:
Libbasic();
void Display();
void DisplayName(char* name);
};
#endif
#ifdef __cplusplus
extern "C" {
void displayfromC();
void displayfromCName(char* name);
}
libbasic.cpp
#include "libbasic.h"
void displayfromC()
{
Libbasic llb;
llb.Display();
}
void displayfromCName(char* name)
{
Libbasic lb;
lb.DisplayName(name);
}
Libbasic::Libbasic()
{
}
void Libbasic::Display()
{
cout <<" C called C++ API \n";
testdemo td;
td.CallingTestDemo();
}
#endif
#endif // LIBBASIC_H
我编译了上面的程序并创建了库 libbasic.a
现在我在 libbasic 文件夹之外创建 C API 文件来调用 C++ 中使用的上述函数
testApi.c
#include<stdio.h>
#include <libbasic.h>
int main()
{
displayfromC();
}
现在我正在尝试使用以下内容创建输出
gcc -o testdemo testApi.c -L ./libbasic -lbasic
其中给出 libbasic.h: no such a file or directory 错误。
基本思想是创建一个可以在任何机器上使用的库和 API 函数。如果我在 C++ 代码中有多个文件夹和头文件,则需要在创建需要导出头文件的 C 应用程序时包含所有文件夹。我不想把所有的源代码都暴露给其他用户。
请告诉我我犯了什么错误以及如何实现这一点。
【问题讨论】:
-
标题和库是分开的,你都需要它们
-
不幸的是,没有minimal reproducible example,没有人可以让您知道任何事情,您应该在收到tour、阅读help center 和学习How to Ask 问题后将其包含在您的问题中,首先,在询问之前。
-
“头文件出错”——这意味着你正在为你的库包含头文件。预处理器应该如何找到它们?用于指定库的
-l选项被预处理器忽略(它由链接器使用,在处理#include指令之后的几个步骤)。更不用说当你编译你的库时,它的头文件的位置在 its 预处理期间被删除了;最终的库文件不知道它的头文件在哪里。 -
您可能想要备份一个步骤 (c.f. XY problem) 并解释为什么您不想使用
-I选项。