Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I statically include a library in g++?

As mentioned in the title, this is a real beginner's question.

I'm realizing that after several years of CS courses and projects and such, I have never actually needed to export an executable that someone else could run without compiling the source manually (which is what most/all professors/TAs do, since they want to see your source code anyway).

So my question is basically this:

When I compile some basic C++ code (e.g. "Hello World" code), I always seem to need some sort of external DLLs to run it.

  • Visual Studio needs the .NET framework.
  • Cygwin needs Cygwin.dll.
  • MinGW needs libgcc_s_dw2-1.dll or something similar.

So how do I simply compile an executable such that I (or someone I give the file to) can just double-click it and have it run? I'm guessing there are some fancy command line flags I can use on g++ to statically link the DLLs; I have simply never needed to do this before.

As I said twice, this is a super beginner question, and yet I could not find (easily, anyway) an answer to this question, StackOverflow or anywhere else. Largely, I think, because the search terms are so commonly used in the descriptions for other problems.

Anyway, all help is appreciated.

EDIT:

I'm literally talking about a Hello World program. e.g.:

HelloWorld.cpp:

#include <iostream>
using namespace std;

int main()
{
    cout << "Hello World!" << endl;

    return 0;
}
like image 970
Ken Bellows Avatar asked Dec 13 '11 04:12

Ken Bellows


People also ask

How do I link a static library?

Static libraries are created by copying all necessary library modules used in a program into the final executable image. The linker links static libraries as a last step in the compilation process. An executable is created by resolving external references, combining the library routines with program code.

Are Lib files static?

In Windows, dll files (dynamically linked libraries) need to be in the same directory as the application or on the search path. lib files (static libraries) need to be statically linked during linking (the last step of building the application).

Which command is used to create static libraries?

To create the library file—which is actually an archive file—we will use ar . We are using the -c (create) option to create the library file, the -r (add with replace) option to add the files to the library file, and the -s (index) option to create an index of the files inside the library file.


1 Answers

Try g++ -static -static-libgcc

like image 171
pinxue Avatar answered Nov 15 '22 10:11

pinxue