I develop a software that needs to be compiled against libraries coming for an external supplier. In some cases the libraries are available as shared libraries (libexample1.so) or as static libraries (libexample1.a).
I want my makefiles to be able to detect that situation. My idea is to check for the static library file, and if it does not exist redefine some compile flags.
My code now is this:
$(PROGRAM1):$(PROGRAM1_OBJS)
ifneq ("$(wildcard $(STATIC_LIB_PATH)","")
#echo "Compiling against static library"
else
#echo "Compiling against dynamic library"
STATIC_LIB_PATH = ""# SETTING IT TO EMPTY
LDFLAGS += -lexample1
endif
(compilation instructions)
This is not working for me as it is trying to execute the STATIC_LIB_PATH... Any suggestions on how to approach this situation? Is this the best approach or are there better ways to do it?
If you want to set make variables, you must do so outside of a recipe. Inside of a recipe, it will be interpreted as a command to execute.
In your case, you can move the assignment before any rule
ifeq ("$(wildcard $(STATIC_LIB_PATH)","")
STATIC_LIB_PATH = # SETTING IT TO EMPTY
LDFLAGS += -lexample1
endif
# ...
$(PROGRAM1):$(PROGRAM1_OBJS)
(compilation instructions)
Usually, you don't need to check for static vs dynamic libraries. The compiler and linker already select the proper library. So, you only need to specify
LDFLAGS += -lexample1
and the linker picks the dynamic version if available, and the static one if there's only a static library.
Related
Is it possible for a linker script to access makefile/shell variables and make a decision based on the said variable?
For example, suppose I want to change the start of the RAM area below without using a different linker script, would it be possible to use a make variable to do this?
MEMORY
{
ifeq ($(SOME_VAR),0)
RAM (wx) : ORIGIN = 0x100000, LENGTH = 128K
else
RAM (wx) : ORIGIN = 0x200000, LENGTH = 128K
endif
}
ld does not import any variables from the environment, so it cannot use them directly. The best way to do this is to create your own linker script with the environment variables you want to export, and have the original linker script include it as so:
makefile:
foo:
echo SOMEVAR=$(SOMEVAR) > environment_linker_script
ld ...
enviroment_linker_script:
SOMEVAR=xxx
master_linker_script:
include environment_linker_script
ifeq ($(SOME_VAR),0) ...
I doubt it although it would depend on the linker you're using. It might be possible for the linker to read some exported variables from make but as I said all this would be dependent on specific linker functionality. Another idea could be as long as the linker file isn't going to be too complicated one option would be to actually generate it using your makefile. There are many examples you could google for about having makefiles generate header files, you could follow the same path for generating a linker file.
If the solution of deciding within the makefile which one of several linker scripts is not sufficient, then generating the script within make might be a viable option.
This solution relies on GNU make's verbatim variables, which get exported to environment variables and are referenced with $$.
I am using this for defining a path variable to be used to include a linker script in another linker script like so:
define LDSCRIPT_DEF
/* Include the original libopencm3 linker script */
INCLUDE $(OPENCM3_DIR)/lib/stm32/f4/stm32f405x6.ld
/* Do custom stuff */
endef
export LDSCRIPT_DEF
$(LDSCRIPT):
#echo "$$LDSCRIPT_DEF" > $(LDSCRIPT)
Explanation: this is a part of the makefile and only works if the makefiles use $(LDSCRIPT) as a prerequisite in all relevant rules.
I know that I can discover the header file dependencies required when building an object file using a few tools (such as gcc -MD ...)
Is there a similar way to determine the static libraries that will be used when a component is linked?
In particular I am looking at some multi-level make files with lots of indirection and I would like to just be able to get a list of the depedencies for that build so I can streamline my build system's rebuild requests.
ex:
make foo.mak
foo.mak
OBJS = bar.o \
bar2.o
DEPS = core\
msg\
utils\
EXTRA_FLAGS += -Wall -Werror
include ../common/common.mak
within common.mak
the members of DEPS will be expanded in various ways depending opn what type of build this is. they may be static, shared or even kernel libraires and they may get pre- or post- fixes.
I would want to get
ABC_core_DEF.a
GEH_msg_IJK.a
(assuming that core and msg were the only dependencies to have expanded to actual static includes and that the pre and post fixes were as shown.)
If your build system supports a mode where the compilation commands are shown (e.g., some setting like VERBOSE=1), you could try and grep this output for items looking like -l (or whatever other kind of linker options your target toolchain uses).
In my SConscript I have the following line:
Program("xtest", Split("main.cpp"), LIBS="mylib fltk Xft Xinerama Xext X11 m")
How do I get scons to use mylib.a instead of mylib.so, while linking dynamically with the other libraries?
EDIT: Looking to use as few platform specific hacks as possible.
Passing the full filepath wrapped in a File node will force static linking. For example:
lib = File('/usr/lib/libfoo.a')
Program('bar', 'main.c', LIBS = [lib])
Will produce the following linker command line
g++ -o bar main.o /usr/lib/libfoo.a
Notice how the "-l" flag is not passed to the linker for this LIBS entry. This effectively forces static linking. The alternative is to modify LINKFLAGS to get what you want with the caveat that you are bypassing the library dependency scanner -- the status of the library will not be checked for rebuilds.
To make this platform independent you append the env['SHLIBSUFFIX'] onto the library you want to use. env['SHLIBSUFFIX'] gives you this environments suffix for shared libraries.
You also have the ['SHLIBPREFIX'], ['LIBPREFIX'], ['LIBSUFFIX'] and ['PROGSUFFIX'], all useful for situations like this.
Edit:
I obviously haven't made myself understood, so I will clarify.
The return value of these lookups are strings to the pre/suffixes that platform uses. In that way you can refer to the file you need on each platform. Note that you cannot use it as a pure string, it has to be embedded as a file node as BennyG suggests. Working with nodes are anyway the best solution as file nodes are much more versatile than a string.
Hope this helps.
I'm trying to get SCons to make a shared library. One of the items going into the .so is a .a static lib.
I have a line like:
env_2.SharedLibrary('libstuff.so', \
Split("""stuff.cxx mylib/libMine.a""")
And upon running it, I get this error:
scons: *** Source file: mylib/libMine.a \
is static and is not compatible with shared target: libstuff.so
However, I know that a shared library can be made from the .a via a command like:
g++ -m32 -shared -o libstuff.so stuff.o mylib/libMine.a
Any ideas on getting this to work or any workarounds would be greatly appreciated.
Related question: How do I get scons to put an additional string -shared on the LINK command line for the Program() call? If I could do this, I think it would meet my needs.
Try to set env['STATIC_AND_SHARED_OBJECTS_ARE_THE_SAME']=1 in your SConstruct.
This problem is not specific to scons. To build a shared library, you'll need objects that are compiled with position independent code (-fPIC). Your best bet is to make the shared library out of the source files compiled with the right options.
In SCons, you can define a list of targets that's used to build both libMine.a and libShared.so.
Update: for your second question, the SharedLibrary builder might do what you need:
SharedLibrary('foo', ['f1.c', 'f2.c', 'f3.c'])
If not, LINKFLAGS sets the flags passed to a link command.
I've the same problem under cygwin. I passed '-fPIC' options to gcc when building the objects and got the following warning:
warning: -fPIC ignored for target (all code is position independent)
I also passed '-shared' to the link command. And I finally got the error
"***.lib is static and is not compatible with shared target: myso.dll"
It seems scons doesn't allow to create so directly from obj or lib files, and one can either create the so from a list of sources files (using SharedLibrary()) or source file + 'LIBS' option like dummytaurus says. I'm curious about that.
env_2.SharedLibrary('libstuff.so', Split("""stuff.cxx"""), LIBS='libMine.a', LIBPATH='mylib')
This should work.
The problem is in the function SharedFlagChecker (Default.py), which checks only for an internal "shared" flag. The SCons documentation leads you to believe that it keeps the distinction between shared objects and static objects via the suffix (SHOBJSUFFIX), but not so. The fix is easy. In the file scons-local.../SCons/Default.py find the SharedFlagCheckerand edit:
def SharedFlagChecker(source, target, env):
same = env.subst('$STATIC_AND_SHARED_OBJECTS_ARE_THE_SAME')
if same == '0' or same == '' or same == 'False':
for src in source:
try:
shared = src.attributes.shared
except AttributeError:
# Replace this line: shared = None
shared = env.Dictionary()['SHOBJSUFFIX'] == src.suffix
if not shared:
raise SCons.Errors.UserError("Source file: ...")
Now objects made via the SharedObject builder will be linkable in a shared library.
The solution to resolve this issue have been used a 'SharedObject' as the following:
ASN1CObjectFile = envCProcesses.SharedObject(target = "OTCMsg.os",
source = "OTCMsg.c",
CFLAGS = envCProcesses["CFLAGS"] + ["-Wno-unused"])
and:
OTCLibSharedLibrary = envCProcesses.SharedLibrary(env["OTC_LIBPATH"] + "/libOTCLib" + env["SHLIBSUFFIX"],
ASN1CObjectFile +
[ASN1AllocatorSource,
"OTCLib.c"],
LIBPREFIX = "")
Best regards,
Same source, all that, just want a static and shared version both. Easy to do?
Yes, it's moderately easy. Just use two "add_library" commands:
add_library(MyLib SHARED source1.c source2.c)
add_library(MyLibStatic STATIC source1.c source2.c)
Even if you have many source files, you can place the list of sources in a Cmake variable, so it's still easy to do.
On Windows you should probably give each library a different name, since there is a ".lib" file for both shared and static. But on Linux and Mac you can even give both libraries the same name (e.g. libMyLib.a and libMyLib.so):
set_target_properties(MyLibStatic PROPERTIES OUTPUT_NAME MyLib)
But I don't recommend giving both the static and dynamic versions of the library the same name. I prefer to use different names because that makes it easier to choose static vs. dynamic linkage on the compile line for tools that link to the library. Usually I choose names like libMyLib.so (shared) and libMyLib_static.a (static). (Those would be the names on linux.)
Since CMake version 2.8.8, you can use "object libraries" to avoid the duplicated compilation of the object files. Using Christopher Bruns' example of a library with two source files:
# list of source files
set(libsrc source1.c source2.c)
# this is the "object library" target: compiles the sources only once
add_library(objlib OBJECT ${libsrc})
# shared libraries need PIC
set_property(TARGET objlib PROPERTY POSITION_INDEPENDENT_CODE 1)
# shared and static libraries built from the same object files
add_library(MyLib_shared SHARED $<TARGET_OBJECTS:objlib>)
add_library(MyLib_static STATIC $<TARGET_OBJECTS:objlib>)
From the CMake docs:
An object library compiles source files but does not archive or link
their object files into a library. Instead other targets created by
add_library() or add_executable() may reference the objects using an
expression of the form $<TARGET_OBJECTS:objlib> as a source, where
objlib is the object library name.
Simply put, the add_library(objlib OBJECT ${libsrc}) command instructs CMake to compile the source files to *.o object files. This collection of *.o files is then referred to as $<TARGET_OBJECT:objlib> in the two add_library(...) commands that invoke the appropriate library creation commands that build the shared and static libraries from the same set of object files. If you have lots of source files, then compiling the *.o files can take quite long; with object libraries you compile them only once.
The price you pay is that the object files must be built as position-independent code because shared libraries need this (static libs don't care). Note that position-independent code may be less efficient, so if you aim for maximal performance then you'd go for static libraries. Furthermore, it is easier to distribute statically linked executables.
There is generally no need to duplicate ADD_LIBRARY calls for your purpose. Just make use of
$> man cmake | grep -A6 '^ *BUILD_SHARED_LIBS$'
BUILD_SHARED_LIBS
Global flag to cause add_library to create shared libraries if on.
If present and true, this will cause all libraries to be built shared unless the library was
explicitly added as a static library. This variable is often added to projects as an OPTION
so that each user of a project can decide if they want to build the project using shared or
static libraries.
while building, first (in one out-of-source directory) with -DBUILD_SHARED_LIBS:BOOL=ON, and with OFF in the other.
Please be aware that previous answers won't work with MSVC:
add_library(test SHARED ${SOURCES})
add_library(testStatic STATIC ${SOURCES})
set_target_properties(testStatic PROPERTIES OUTPUT_NAME test)
CMake will create test.dll together with test.lib and test.exp for shared target. Than it will create test.lib in the same directory for static target and replace previous one. If you will try to link some executable with shared target it will fail with error like:
error LNK2001: unresolved external symbol __impl_*.`.
Please use ARCHIVE_OUTPUT_DIRECTORY and use some unique output directory for static target:
add_library(test SHARED ${SOURCES})
add_library(testStatic STATIC ${SOURCES})
set_target_properties(
testStatic PROPERTIES
OUTPUT_NAME test
ARCHIVE_OUTPUT_DIRECTORY testStatic
)
test.lib will be created in testStatic directory and won't override test.lib from test target. It works perfect with MSVC.
It's possible to pack eveything in the same compilation breath, as suggested in the previous answers, but I would advise against it, because in the end it's a hack that works only for simple projects. For example, you may need at some point different flags for different versions of the library (esp. on Windows where flags are typically used to switch between exporting symbols or not). Or as mentionned above, you may want to put .lib files into different directories depending on whether they correspond to static or shared libraries. Each of those hurdles will require a new hack.
It may be obvious, but one alternative that has not been mentionned previously is to make the type of the library a parameter:
set( ${PROJECT_NAME}_LIBTYPE CACHE STRING "library type" )
set_property( CACHE ${PROJECT_NAME}_LIBTYPE PROPERTY STRINGS "SHARED;STATIC" )
add_library( ${PROJECT_NAME} ${PROJECT_NAME}_LIBTYPE ${SOURCE_FILES} )
Having shared and static versions of the library in two different binary trees makes it easier to handle different compilation options. I don't see any serious drawback in keeping compilation trees distinct, especially if your compilations are automated.
Note that even if you intend to mutualize compilations using an intermediate OBJECT library (with the caveats mentionned above, so you need a compelling reason to do so), you could still have end libraries put in two different projects.