相关疑难解决方法(0)

为什么要从.o创建.a文件进行静态链接?

考虑以下代码:

one.c:

#include <stdio.h>

int one() {
   printf("one!\n");
   return 1;
}
Run Code Online (Sandbox Code Playgroud)

two.c:

#include <stdio.h>

int two() {
   printf("two!\n");
   return 2;
}
Run Code Online (Sandbox Code Playgroud)

prog.c中

#include <stdio.h>

int one();
int two();

int main(int argc, char *argv[]) 
{
   one();
   two();

   return 0;
}
Run Code Online (Sandbox Code Playgroud)

我想将这些程序链接在一起.所以我这样做:

gcc -c -o one.o one.c
gcc -c -o two.o two.c
gcc -o a.out prog.c one.o two.o
Run Code Online (Sandbox Code Playgroud)

这很好用.

或者我可以创建一个静态库:

ar rcs libone.a one.o
ar rcs libtwo.a two.o
gcc prog.c libone.a libtwo.a
gcc -L. prog.c -lone -ltwo
Run Code Online (Sandbox Code Playgroud)

所以我的问题是:为什么我会使用第二个版本 - 我创建了一个".a"文件 - 而不是链接我的".o"文件?它们似乎都是静态链接,所以它们之间是否有优势或架构差异?

c linux gcc static-linking

21
推荐指数
2
解决办法
1万
查看次数

如何在Googletest框架的多个测试中将全局变量用于“配置”

我正在使用C ++的Google测试框架。每个文件都包含一个config.hpp,它定义了一个全局配置变量。我想在变量而不是编译时const或中定义我的配置constexpr。如何定义依赖项,以便在链接在一起的不同文件中具有相同的变量?我必须使用单身人士吗?我可以避免吗?有没有更好的推荐方法来使用多个测试文件的xUnit样式?

我的配置文件 config.hpp

#pragma once
struct {
    const float tolerance = 0.001;
    // ...
} CONFIG_VAR;
Run Code Online (Sandbox Code Playgroud)

每个测试* .cpp源文件都类似于:

#include "gtest/gtest.h"
#include "core/config.hpp"
TEST(a, b) { ... }
Run Code Online (Sandbox Code Playgroud)

我的主文件:

#include "gtest/gtest.h"
int main(int argc, char **argv) {
    ::testing::InitGoogleTest(&argc, argv);
    return RUN_ALL_TESTS();
}
Run Code Online (Sandbox Code Playgroud)

我使用以下命令进行编译和链接:

em++  -I $GTEST_ROOT/googletest/include main_all_tests.cpp test_*.cpp
Run Code Online (Sandbox Code Playgroud)

PS。我的问题是变量CONFIG_VAR的多个定义。

我的解决方案基于一个相关的问题

c++ googletest emscripten

2
推荐指数
1
解决办法
2011
查看次数

标签 统计

c ×1

c++ ×1

emscripten ×1

gcc ×1

googletest ×1

linux ×1

static-linking ×1