c++ - 如何共享我的 C/C++ 项目并隐藏部分源代码?

标签 c++ c unix shared-libraries static-libraries

我想分享我用 C/C++(Linux 环境 gcc/g++ 编译器)编写的项目作为共享库/静态库,而不实际共享源代码。这样其他用户就可以在不知道我的源代码的情况下使用我的项目。谁能告诉我如何以 .so/.a 格式共享它?

假设,我的项目如下所示:

main.cpp , source1.cpp, source2.cpp, source3.cpp, head1.h, 生成文件

如何通过隐藏文件source1.cppsource2.cppsource3.cpp 和将它们作为共享库/静态库。 ma​​in.cpp 文件包含 main() 函数。具体流程是什么?

PS:我是共享库/静态库的新手。

最佳答案

假设您有以下源文件:

mylib.c:

#include <stdio.h>

void my_print(int i)
{
    printf("i=%d\n", i);
}

这个的公共(public) header 是:

mylib.h:

#ifndef MYLIB_H
#define MYLIB_H

void my_print(int i);

#endif

然后您可以像这样构建库:

gcc -g -Wall -Wextra -c mylib.c
gcc -g -Wall -Wextra -shared -fPIC -o libmylib.so mylib.o

然后您可以将 libmylib.so 和 mylib.h 分发给用户。然后可以像这样在他们的代码中使用它:

用户程序.c:

#include "mylib.h"

int main()
{
    my_print(5);
    return 0;
}

然后他们会把 libmylib.so 放到/usr/lib 或/usr/local/lib 这样的地方,然后像这样编译:

gcc -g -Wall -Wextra -o user_prog user_prog.c -l mylib

对于您的特定情况,假设 head1.h 包含公共(public)接口(interface)和 source1.cpp source2.cpp source3.cpp 库,您将像这样编译:

g++ -g -Wall -Wextra -c source1.cpp
g++ -g -Wall -Wextra -c source2.cpp
g++ -g -Wall -Wextra -c source3.cpp
g++ -g -Wall -Wextra -shared -fPIC -o libmylib.so source1.o source2.o source3.o

关于c++ - 如何共享我的 C/C++ 项目并隐藏部分源代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48571392/

相关文章:

linux - Rsync——排除目录但包括该目录中的特定子目录

C++ char16_t 的大小取决于什么?

c++:为什么不能使用模板来推断容器和元素类型?

c - 通过 int 值访问地址

c - 如何在CUDA程序中调试?输出异常

linux - 如何检查awk数组是否为空

c++ - 缓冲区溢出 :codesonar warning

c++ - gcc ld : method to determine link order of static libraries

c - 如何确定 va_arg 列表的结尾?

linux - 使用 awk 对常见元素进行分组