How to set a define through "./configure" with Autoconf - c++

I have one project that can generate two diferent applications based on one define.
libfoo_la_CXXFLAGS = -DMYDEFINE
I have to modify the Makefile.am to set this define, so it is not automatic.
Can I set this define somehow through the configure command?
Is there any other way to set one define using autotools?

You have to edit the file configure.ac, and before AC_OUTPUT (which is the last thing in the file) add a call to AC_DEFINE.
In a simple case like yours, it should be enough with:
AC_DEFINE(MYDEFINE)
If you want to set a value, you use:
AC_DEFINE(MYDEFINE, 123)
This last will add -DMYDEFINE=123 to the flags (DEFS = in Makefile), and #define MYDEFINE 123 in the generated autoconf header if you use that.
I recommend you read the documentation from the beginning, and work through their examples and tutorials. Also check other projects' configure files to see how they use different features.
Edit: If you want to pass flags on the command line to the make command, then you do something like this:
libfoo_la_CXXFLAGS = $(MYFLAGS)
Then you call make like this:
$ make MYFLAGS="-DMYDEFINE"
If you don't set MYFLAGS on the command line, it will be undefined and empty in the makefile.
You can also set target-specific CPPFLAGS in Makefile.am, in which case the source files will be recompiled, once for each set of flags:
lib_LTLIBRARIES = libfoo.la libbar.la
libfoo_la_SOURCES = foo.c
libfoo_la_CPPFLAGS = -DFOO
libbar_la_SOURCES = foo.c
libbar_la_CPPFLAGS = -DBAR

These days autoheader demands
AC_DEFINE([MYDEFINE], [1], [Description here])

Related

GNU make - rule in makefile in $(MAKEFILES) is not read/acknowledged

I have a makefile, ImpTarget.mk, defined with following content, taken from this example:
%.h: %.dummy_force
#echo header= $# xyz
%.dummy_force: ;
I include this file in the MAKEFILES variable
This is my top-level makefile (modified with the MAKEFILES variable)
MAKEFILES = "C:\Users\User1\Desktop\A\ImpTarget.mk"
all:
$(MAKE) -C src -f makefile_gen all
$(MAKE) -C src DEBUG=TRUE -f makefile_gen all
My goal is to turn all files - .h, .cpp, etc - in the prerequisites list into targets also i.e., executing make --print-database should yield a statement that every header file is also a target.
However, it's not working.
When I look at the database printed out, for each makefile I see that MAKEFILES is equal to "C:\Users\User1\Desktop\A\ImpTarget.mk" which is good because it means that it should be reading in ImpTarget.mk
3.4 The Variable MAKEFILES
If the environment variable MAKEFILES is defined, make considers its
value as a list of names (separated by whitespace) of additional
makefiles to be read before the others.
But it is not turning each file into a target. I still get:
# Not a target:
C:/Users/User1/Desktop/A/HMI_FORGF/qt5binaries/include/QtCore/qglobalstatic.h:
# Implicit rule search has been done.
# Last modified 2016-05-12 10:10:13
# File has been updated.
# Successfully updated.
In fact, the rule I defined is not even showing up in the --print-data-base part of the output.
I put the xyz as a marker so I could easily locate it in the listing of the rules that are executed but it doesn't appear in that list.
Why not use include?
Well first of all, what's the difference? Show me a link.
Secondly, yes that's the preferred method but some of my makefiles auto-generate a makefile, then inside that one generate another makefile and execute it.
So I don't have control over my build system enough to do that.
If the environment variable MAKEFILES is defined
Meaning make will only consider MAKEFILES if it is defined externally to make, either in the shell environment itself or by running make MAKEFILES=foo.mk.
MAKEFILES vs include is explained in the next paragraph
The main use of MAKEFILES is in communication between recursive invocations of make
You need to export the MAKEFILE variable into the environment. From 6.10 Variables from the Environment
When make runs a recipe, variables defined in the makefile are placed into the environment of each shell. This allows you to pass values to sub-make invocations (see Recursive Use of make). By default, only variables that came from the environment or the command line are passed to recursive invocations. You can use the export directive to pass other variables. See Communicating Variables to a Sub-make, for full details.
Since MAKEFILES wasn't found in the original environment, it isn't automatically passed into the environment. Use:
export MAKEFILES = "C:\Users\User1\Desktop\A\ImpTarget.mk"

Automake AM_LDADD workaround

I want to set the same LDADD attribute (Unit test library) to a large number of targets (unit test C++ files). I first though that maybe automake has AM_LDADD variable to add that library to all the targets within the file but is not the case.
In some mail list I found some short discussion asking to add it:
http://gnu-automake.7480.n7.nabble.com/AM-LIBS-AM-LDADD-td3698.html
My question is, how do you deal with that? is it there any way to avoid manually adding LDADD attribute to each target?
So far my Makefile.am looks like:
test1_SOURCES = ...
test1_LDADD = -llibrary
...
...
test20_SOURCES = ...
test20_LDADD = -llibrary
The equivalent of an AM_LDADD variable is simply LDADD. e.g.,
LDADD = -llibrary
test1_SOURCES = ...
...
test20_SOURCES = ...
If you need to override LDADD for a particular program: prog, then prog_LDADD will always take precedence.
I always assumed that since there was no LDADD standard environment variable passed to configure - as you can see with configure --help - there is no real reason for an AM_LDADD. This kind of makes sense, as the configure script, and any options, e.g., --with-foo=<path> should (ideally) work out the library dependencies.
On the other hand, passing CFLAGS via configure might still need an AM_CFLAGS that combines CFLAGS and with other compiler flags determined by the configure script; or even a foo_CFLAGS override. Since configure must be informed of your custom CFLAGS.
Also, I don't know if the test<n> programs only take a single C++ source file, but if so, you can simplify the Makefile.am with:
LDADD = -llibrary
check_PROGRAMS = test1 test2 ... test20
AM_DEFAULT_SOURCE_EXT = .cc # or .cpp
as described here.
In regards to your comment, your can use a convenience library for that purpose - which is particularly useful for common code used by test programs:
noinst_LIBRARIES = libfoo.a # or noinst_LTLIBRARIES = libfoo.la
libfoo_a_SOURCES = MyClass.hh MyClass.cc # or libfoo_la_SOURCES
LDADD = ./libfoo.a -llibrary # or libfoo.la if using libtool.
... etc ...
It's a bad idea to modify LDADD in your Makefile.am, even if it seems convenient. It will make your build system very fragile.
In particular, if the user attempts to override LDADD from the make command line, then your definition of LDADD in Makefile.am will disappear. It's not unreasonable to expect that a user might override LDADD, so you should definitely protect yourself against this situation.
Your original definitions of test1_LDADD, ...,test20_LDADD are much more robust and, as far as I understand the automake manual, the recommended use.
See the remarks here for more info:
https://www.gnu.org/software/automake/manual/html_node/User-Variables.html
https://www.gnu.org/software/automake/manual/html_node/Flag-Variables-Ordering.html

Setting and using path to data directory with GNU AutoTools

I am trying to use GNU AutoTools for my C++ project. I have written configure.ac, makefile.am etc. I have some files that are used by the program during execution e.g. template files, XML schema etc. So, I install/copy these files along the executable, for which I use something like:
abcdir = $(bindir)/../data/abc/
abc_DATA = ../data/knowledge/abc.cc
Now it copies the file correctly and My program installation structure looks somethings as follows:
<installation_dir>/bin/<executableFile>
<installation_dir>/data/abc/abc.cc
Now the problem is that in the source code I actually use these files (abc.cc etc.) and for that I need path of where these files resides to open them. One solution is to define (using AC_DEFINE) some variable e.g. _ABC_PATH_ that points to the path of installation but how to do that exactly?. OR is there any better way to do that. For example, in source code, I do something like:
...
ifstream input(<path-to-abc-folder> + "abc.cc"); // how to find <path-to-abc-folder>?
..
The AC_DEFINE solution is fine in principle, but requires shell-like variable expansion to take place. That is, _ABC_PATH_ would expand to "${bindir}/../data/abs", not /data/abc.
One way is to define the path via a -D flag, which is expanded by make:
myprogram_CPPFLAGS += -D_ABC_PATH='\"${abcdir}\"'
which works fine in principle, but you have to make include config.status in the dependencies of myprogram.
If you have a number of such substitution variables, you should roll out a paths.h file that is
generated by automake with a rule like:
paths.h : $(srcdir)/paths.h.in config.status
sed -e 's:#ABC_PATH#:${abcdir}:' $< > $#
As a side-note, you do know about ${prefix} and ${datarootdir} and friends, don't you? If not, better read them up; ${bindir}/.. is not necessarily equal to ${prefix} if the user did set ${exec_prefix}.

CXXSources-- what are they?

I'm new to compiling C/C++ with the aid of make. I downloaded an open source project and noticed that there is in the make file CXXSources and CXXObjects. I think I understand roughly what the make file is doing with them but...
I don't have any of the source files listed under CXXSources. Are these like dependences I'm supposed to know how to find? Is there any custom as to what CXXSource is versus just Source?
Added link to project: http://www.fim.uni-passau.de/en/fim/faculty/chairs/theoretische-informatik/projects.html
More specifically, the GML parser, eg. http://www.fim.uni-passau.de/fileadmin/files/lehrstuhl/brandenburg/projekte/gml/gml-parser.tar.gz
It seems to be getting stuck on the line:
gml_to_graph : $(CXXOBJECTS) gml_scanner.o gml_parser.o
$(CXX) -o gml_to_graph_demo $(CXXOBJECTS) gml_parser.o gml_scanner.o -L$(LEDADIR)/lib -lG -lL -lm
The $CXXObjects is defined by
CXXSOURCES = gml_to_graph.cc gml_to_graph_demo.cc
CXXOBJECTS = $(CXXSOURCES:.cc=.o)
So I need gml_to_graph.cc, it seems. Or maybe I'm wrong?
Usually, the variables are set before the point where you see them. This could be
(a) via the environment
(b) before including the quoted makefile
(c) in the quoted makefile, but preceding the location quoted
To see (verbosely) what GNU make takes into account, do:
make -Bn
(it will show everything that _would get executed)
Even more verbose:
make -p all
It will show you all the internal variable expansions.
If you post a link or more information, we will be able to come up with less generic (and hence possibly less confusing) answers

Best practice for dependencies on #defines?

Is there a best practice for supporting dependencies on C/C++ preprocessor flags like -DCOMPILE_WITHOUT_FOO? Here's my problem:
> setenv COMPILE_WITHOUT_FOO
> make <Make system reads environment, sets -DCOMPILE_WITHOUT_FOO>
<Compiles nothing, since no source file has changed>
What I would like to do is have all files that rely on #ifdef statements get recompiled:
> setenv COMPILE_WITHOUT_FOO
> make
g++ FileWithIfdefFoo.cpp
What I do not want to is have to recompile everything if the value of COMPILE_WITHOUT_FOO has not changed.
I have a primitive Python script working (see below) that basically writes a header file FooDefines.h and then diffs it to see if anything is different. If it is, it replaces FooDefines.h and then the conventional source file dependency takes over. The define is not passed on the command line with -D. The disadvantage is that I now have to include FooDefines.h in any source file that uses the #ifdef, and also I have a new, dynamically generated header file for every #ifdef. If there's a tool to do this, or a way to avoid using the preprocessor, I'm all ears.
import os, sys
def makeDefineFile(filename, text):
tmpDefineFile = "/tmp/%s%s"%(os.getenv("USER"),filename) #Use os.tempnam?
existingDefineFile = filename
output = open(tmpDefineFile,'w')
output.write(text)
output.close()
status = os.system("diff -q %s %s"%(tmpDefineFile, existingDefineFile))
def checkStatus(status):
failed = False
if os.WIFEXITED(status):
#Check return code
returnCode = os.WEXITSTATUS(status)
failed = returnCode != 0
else:
#Caught a signal, coredump, etc.
failed = True
return failed,status
#If we failed for any reason (file didn't exist, different, etc.)
if checkStatus(status)[0]:
#Copy our tmp into the new file
status = os.system("cp %s %s"%(tmpDefineFile, existingDefineFile))
failed,status = checkStatus(status)
print failed, status
if failed:
print "ERROR: Could not update define in makeDefine.py"
sys.exit(status)
This is certainly not the nicest approach, but it would work:
find . -name '*cpp' -o -name '*h' -exec grep -l COMPILE_WITHOUT_FOO {} \; | xargs touch
That will look through your source code for the macro COMPILE_WITHOUT_FOO, and "touch" each file, which will update the timestamp. Then when you run make, those files will recompile.
If you have ack installed, you can simplify this command:
ack -l --cpp COMPILE_WITHOUT_FOO | xargs touch
I don't believe that it is possible to determine automagically. Preprocessor directives don't get compiled into anything. Generally speaking, I expect to do a full recompile if I depend on a define. DEBUG being a familiar example.
I don't think there is a right way to do it. If you can't do it the right way, then the dumbest way possible is probably the your best option. A text search for COMPILE_WITH_FOO and create dependencies that way. I would classify this as a shenanigan and if you are writing shared code I would recommend seeking pretty significant buy in from your coworkers.
CMake has some facilities that can make this easier. You would create a custom target to do this. You may trade problems here though, maintaining a list of files that depend on your symbol. Your text search could generate that file if it changed though. I've used similar techniques checking whether I needed to rebuild static data repositories based on wget timestamps.
Cheetah is another tool which may be useful.
If it were me, I think I'd do full rebuilds.
Your problem seems tailor-made to treat it with autoconf and autoheader, writing the values of the variables into a config.h file. If that's not possible, consider reading the "-D" directives from a file and writing the flags into that file.
Under all circumstances, you have to avoid builds that depend on environment variables only. You have no way of telling when the environment changed. There is a definitive need to store the variables in a file, the cleanest way would be by autoconf, autoheader and a source and multiple build trees; the second-cleanest way by re-configure-ing for each switch of compile context; and the third-cleanest way a file containing all mutable compiler switches on which all objects dependant on these switches depend themselves.
When you choose to implement the third way, remember not to update this file unnecessarily, e.g. by constructing it in a temporary location and copying it conditionally on diff, and then make rules will be capable of conditionally rebuilding your files depending on flags.
One way to do this is to store each #define's previous value in a file, and use conditionals in your makefile to force update that file whenever the current value doesn't match the previous. Any files which depend on that macro would include the file as a dependency.
Here is an example. It will update file.o if either file.c changed or the variable COMPILE_WITHOUT_FOO is different from last time. It uses $(shell ) to compare the current value with the value stored in the file envvars/COMPILE_WITHOUT_FOO. If they are different, then it creates a command for that file which depends on force, which is always updated.
file.o: file.c envvars/COMPILE_WITHOUT_FOO
gcc -DCOMPILE_WITHOUT_FOO=$(COMPILE_WITHOUT_FOO) $< -o $#
ifneq ($(strip $(shell cat envvars/COMPILE_WITHOUT_FOO 2> /dev/null)), $(strip $(COMPILE_WITHOUT_FOO)))
force: ;
envvars/COMPILE_WITHOUT_FOO: force
echo "$(COMPILE_WITHOUT_FOO)" > envvars/COMPILE_WITHOUT_FOO
endif
If you want to support having macros undefined, you will need to use the ifdef or ifndef conditionals, and have some indication in the file that the value was undefined the last time it was run.
Jay pointed out that "make triggers on date time stamps on files".
Theoretically, you could have your main makefile, call it m1, include variables from a second makefile called m2. m2 would contain a list of all the preprocessor flags.
You could have a make rule for your program depend on m2 being up-to-date.
the rule for making m2 would be to import all the environment variables ( and thus the #include directives ).
the trick would be, the rule for making m2 would detect if there was a diff from the previous version. If so, it would enable a variable that would force a "make all" and/or make clean for the main target. otherwise, it would just update the timestamp on m2 and not trigger a full remake.
finally, the rule for the normal target (make all ) would source in the preprocessor directives from m2 and apply them as required.
this sounds easy/possible in theory, but in practice GNU Make is much harder to get this type of stuff to work. I'm sure it can be done though.
make triggers on date time stamps on files. A dependent file being newer than what depends on it triggers it to recompile. You'll have to put your definition for each option in a separate .h file and ensure that those dependencies are represented in the makefile. Then if you change an option the files dependent on it would be recompiled automatically.
If it takes into account include files that include files you won't have to change the structure of the source. You could include a "BuildSettings.h" file that included all the individual settings files.
The only tough problem would be if you made it smart enough to parse the include guards. I've seen problems with compilation because of include file name collisions and order of include directory searches.
Now that you mention it I should check and see if my IDE is smart enough to automatically create those dependencies for me. Sounds like an excellent thing to add to an IDE.