简体   繁体   中英

How to create a static library that is statically linked against c/c++ standard libraries?

I want to create a trivial static library my_math.lib . Its header and source files are given as follows.

// my_math.h
#ifndef MY_MATH_H
#define MY_MATH_H

double reciprocal(double d);
#endif

// my_math.cpp
#include "my_math.h"
#include <iostream>
double reciprocal(double d)
{
    std::cout << __func__ << std::endl;

    return 1.0 / d;
}

For the sake of learning purposes, I compile it in discreate steps as follows:

  1. Preprocessing: cpp my_math.cpp > my_math.ii
  2. Compiling: g++ -S my_math.ii (where the output is my_math.s by default)
  3. Assembling: as my_math.s -o my_math.o
  4. Archiving: ar rvs my_math.a my_math.o

Question

As you can see, my library above uses cout defined in c/c++ standard libraries.

For academic purposes, is it possible to create a static library my_math.lib that statically links against c/c++ libraries? I did not find any articles that show how to do so.

Can we extend the archiving step to also include static linking against c/c++ standard libraries? In other words, is it possible to use -static option provided by g++ when creating static libraries?

Edit:

As the expected my_math.lib contains both my own code and c/c++ standard libraries, someone who uses my_math.lib will only need to have both my_math.h and iostream , and statically links against my_math.lib . The resulting .exe binary does not need c/c++ runtime anymore. This is the scenario I want to achieve for academic purposes!

Thank you PeterT 在此处输入图像描述 for informing me a link about how to merge two archives or static libraries .

I hope this answer is also useful for others in the future. Here I want to merge my_math.a with libstdc++.a .

  1. Extract my_math.o from my_math.a with ar x my_math.a .
  2. Also extract all object .o files from libstdc++.a with ar x libstdc++.a .
  3. Optionally remove both archives with del my_math.a and del libstdc++.a .
  4. Archive all object files with ar c libmerged.a *.o .

Done.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM