Simple question- are these any way to not have to call libraries during the compiling? I mean, I would like to simply call g++ main.cpp without calling g++ main.cpp -lGL -lGLU -lGLEW -lSTL -lMyMother and so on... I know, makefiles or simple shell scripting, but I would like to make it elegant way - call these libraries inside cpp code - something like 'using GL;'.
-
1No, unlike VC++ there is no way to tell GCC which libraries to link to by specifying it in the source code. Use a makefile. – Jonathan Wakely Oct 29 '14 at 19:45
3 Answers
Since you're using GCC, you could create/modify a specs file to add the flags you want.
If you don't like typing flags, you really should be using a makefile, though.
- 219,201
- 40
- 422
- 469
-
Well I suppose you are right - there is a reason everyone are using Makefiles. ;) – Cheshire Cat Oct 29 '14 at 19:24
-
1Don't modify the specs file to add libraries inside them. – Basile Starynkevitch Oct 29 '14 at 19:40
Technically you can dynamically load libraries by dlopen() and call functions from it (I am assuming you are on *nix). Though that would be not the same thing and I doubt will make your life easier. Other than that there is no portable way of specifying which library to use in source file.
- 43,454
- 1
- 47
- 90
-
Thanks, gotta try this method. I should only remember that if something won't work it's because my laziness. – Cheshire Cat Oct 29 '14 at 19:24
On Linux you may use pkg-config and shell expansion. Use pkg-config --list-all to discover what packages are known to it (you might add a .pc file to add a new package). For instance, a GTK application mygtkapp.c could be compiled with
gcc -Wall -g $(pkg-config --cflags gtk+-x11-3.0) -c mygtkapp.c
then later linked with
gcc -g mygtkapp.o $(pkg-config --libs gtk+-x11-3.0) -o mygtkapp
Notice that order of arguments to gcc always matter. Of course use g++ to compile C++ applications with GCC.
Consider also using a Makefile like this one. Then just type make to build your software (and e.g. make clean to clean the build tree).
You might use weird tricks in your Makefile to e.g. parse with awk some comments in your C++ code to feed make but I think it is a bad idea.
Technically, you still pass -I and -D flags (at compile time) and -L and -l flags (at link time) to gcc or g++ but the pkg-config utility (or make ....) is generating these flags.
If you edit your source code with emacs you could add a comment at end of your C file to set some compilation command for emacs, see this.
PS. I don't recommend configuring your GCC spec files for such purposes.
- 1
- 1
- 223,805
- 18
- 296
- 547