forked from MRtrix3/mrtrix3
-
Notifications
You must be signed in to change notification settings - Fork 6
/
configure
executable file
·1401 lines (1013 loc) · 38.5 KB
/
configure
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# pylint: disable=invalid-name
usage_string = '''
USAGE
[ENV] ./configure [-debug] [-assert] [-profile] [-nogui] [-noshared]
DESCRIPTION
In most cases, a simple invocation should work:
$ ./configure
This creates a 'config' file containing the parameters of the buid (PATH,
compiler flags, etc.). A number of options are provided to modify the build
for debugging and other purposes (see OPTIONS below). For example:
$ ./configure -debug -assert
will generate a config file with debugging symbols and assertions enabled.
Other parameters are controlled by setting environment variables (see
ENVIRONMENT VARIABLES below). For example:
$ ARCH=x86-64 ./configure
will produce a config file to run on a generic AMD64 CPU.
OPTIONS
-debug enable debugging symbols.
-assert enable all assert() and related checks.
-nooptim disable optimisation (implied by -debug and -profile).
-profile enable profiling.
-nogui disable GUI components.
-noshared disable shared library generation.
-static produce statically-linked executables.
-verbose enable more informative output.
-dev enable the extended development build process.
-R used to generate an R module (implies -noshared).
-openmp enable OpenMP compiler flags.
ENVIRONMENT VARIABLES
For non-standard setups, you may need to supply additional information
using environment variables. For example, to set the compiler, use:
$ CXX=/usr/local/bin/g++-5.5 ./configure
Alternatively:
$ export CXX=/usr/local/bin/g++-5.5
$ ./configure
Multiple environment variables can be set this way as needed.
The following environment variables are available:
CXX
The compiler command to use. The default is "clang++", falling back to
"g++" if not found.
CXX_ARGS
The arguments expected by the compiler. The default is:
"-c CFLAGS SRC -o OBJECT"
LD
The linker command to use. The default is the same as CXX.
LD_ARGS
The arguments expected by the linker. The default is:
"LDFLAGS OBJECTS -o EXECUTABLE"
LDLIB_ARGS
The arguments expected by the linker for generating a shared library.
The default is:
"-shared LDLIB_FLAGS OBJECTS -o LIB"
ARCH
the specific CPU architecture to compile for. This variable will be
passed to the compiler using -march=$ARCH. You can use 'ARCH=native' to
get the best performance for your system. Note that this will result in
executables that may not run on other systems if the same CPU
extensions are not available.
CFLAGS
Any additional flags to the compiler.
LDFLAGS
Any additional flags to the linker.
LDLIB_FLAGS
Any additional flags to the linker to generate a shared library.
EIGEN_CFLAGS
Any flags required to compile with Eigen3. This may include in
particular the path to the include files, if not in a standard location
For example:
$ EIGEN_CFLAGS="-isystem /usr/local/include/eigen3" ./configure
ZLIB_CFLAGS
Any flags required to compile with the zlib compression library.
ZLIB_LDFLAGS
Any flags required to link with the zlib compression library.
TIFF_CFLAGS
Any flags required to compile with the TIFF library.
TIFF_LDFLAGS
Any flags required to link with the TIFF library.
FFTW_CFLAGS
Any flags required to compile with the FFTW library.
FFTW_LDFLAGS
Any flags required to link with the FFTW library.
QMAKE
The command to invoke Qt's qmake (default: qmake).
MOC
The command to invoke Qt's meta-object compile (default: moc)
RCC
The command to invoke Qt's resource compiler (default: rcc)
PATH
Set the path to use during the configure process. This may be useful
to set the path to Qt's qmake. For example:
$ PATH=/usr/local/bin:$PATH ./configure
Note that this path will be stored in the config file and used during
subsequent invocations of the build process. It only needs to be
specified correctly at configure time.
'''
import subprocess, sys, os, platform, tempfile, shlex, re, copy
system = platform.system().lower()
# on Windows, need to use MSYS2 version of python - not MinGW version:
if sys.executable[0].isalpha() and sys.executable[1] == ':':
python_cmd = subprocess.check_output ([ 'cygpath.exe', '-w', '/usr/bin/python' ]).decode(errors='ignore').splitlines()[0].strip()
sys.exit (subprocess.call ([ python_cmd ] + sys.argv))
debug = False
asserts = False
profile = False
nogui = False
noshared = False
static = False
verbose = False
R_module = False
openmp = False
dev = False
optimlevel = 3
for arg in sys.argv[1:]:
if '-debug'.startswith (arg):
debug = True
optimlevel = 0
elif '-dev'.startswith (arg):
dev = True
elif '-assert'.startswith (arg):
asserts = True
elif '-nooptim'.startswith (arg):
optimlevel = 0
elif '-profile'.startswith (arg):
profile = True
optimlevel = 0
elif '-nogui'.startswith (arg):
nogui = True
elif '-noshared'.startswith (arg):
noshared = True
elif '-static'.startswith (arg):
static = True
noshared = True
elif '-verbose'.startswith (arg):
verbose = True
elif '-R'.startswith (arg):
R_module = True
#noshared = True
nogui = True
elif '-openmp'.startswith (arg):
openmp = True
else:
sys.stdout.write (usage_string)
sys.exit (1)
logfile = open (os.path.join (os.path.dirname(sys.argv[0]), 'configure.log'), 'wb')
config_report = ''
def log (message):
global logfile
logfile.write (message.encode (errors='ignore'))
if verbose:
sys.stdout.write (message)
sys.stdout.flush()
def report (message):
global config_report, logfile
config_report += message
sys.stdout.write (message)
sys.stdout.flush()
logfile.write (('\nREPORT: ' + message.rstrip() + '\n').encode (errors='ignore'))
def error (message):
global logfile
logfile.write (('\nERROR: ' + message.rstrip() + '\n\n').encode (errors='ignore'))
sys.stdout.write ('\nERROR: ' + message.rstrip() + '\n\n')
sys.stdout.flush()
sys.exit (1)
if profile:
build_type = 'profiling version'
elif debug:
build_type = 'debug version'
else:
build_type = 'release version'
build_options = []
if asserts:
build_options.append ('asserts')
if optimlevel <= 1:
build_options.append ('nooptim')
if nogui:
build_options.append ('nogui')
if noshared:
build_options.append ('noshared')
if static:
build_options.append ('static')
if openmp:
build_options.append ('openmp')
if build_options:
build_type += ' with ' + ', '.join (build_options)
report ("""
MRtrix3Tissue build type requested: """ + build_type + '\n\n' + 'MRtrix3Tissue is a fork of the MRtrix3 project' + '\n\n')
# remove any mention of anaconda from PATH:
path = os.environ['PATH']
if path.endswith ('\\'):
path = path[:-1]
oldpath = path.split(':')
cleanpath = [ entry for entry in oldpath if 'anaconda' not in entry.lower() ]
if not oldpath == cleanpath:
report ('WARNING: Anaconda removed from PATH to avoid conflicts\n\n')
path = os.pathsep.join(cleanpath)
os.environ['PATH'] = path
cpp = ld = None
cxx = [ 'clang++', 'g++' ]
cxx_args = '-c CFLAGS SRC -o OBJECT'.split()
cpp_flags = [ '-std=c++11', '-DMRTRIX_BUILD_TYPE="'+build_type+'"' ]
ld_args = 'OBJECTS LDFLAGS -o EXECUTABLE'.split()
ld_flags = []
if system != 'darwin':
ld_flags += [ '-Wl,--sort-common,--as-needed' ]
if static:
ld_flags += [ '-static', '-Wl,-u,pthread_cancel,-u,pthread_cond_broadcast,-u,pthread_cond_destroy,-u,pthread_cond_signal,-u,pthread_cond_wait,-u,pthread_create,-u,pthread_detach,-u,pthread_cond_signal,-u,pthread_equal,-u,pthread_join,-u,pthread_mutex_lock,-u,pthread_mutex_unlock,-u,pthread_once,-u,pthread_setcancelstate' ]
ld_lib_args = 'OBJECTS LDLIB_FLAGS -o LIB'.split()
class TempFile(object):
def __init__ (self, suffix):
self.fid = None
self.name = None
[ fid, self.name ] = tempfile.mkstemp (suffix)
self.fid = os.fdopen (fid, 'w')
def __enter__ (self):
return self
def __exit__(self, exception_type, value, traceback):
try:
os.unlink (self.name)
except OSError as excp:
log ('error deleting temporary file "' + self.name + '": ' + excp.strerror)
class DeleteAfter(object):
def __init__ (self, name):
self.name = name
def __enter__ (self):
return self
def __exit__(self, exception_type, value, traceback):
try:
os.unlink (self.name)
except OSError as excp:
log ('error deleting temporary file "' + self.name + '": ' + excp.strerror)
class TempDir(object):
def __init__ (self):
self.name = tempfile.mkdtemp()
def __enter__ (self):
return self
def __exit__(self, exception_type, value, traceback):
try:
for basename in os.listdir (self.name):
fullpath = os.path.join (self.name, basename)
if os.path.isdir (fullpath):
os.rmdir (fullpath)
else:
os.unlink (fullpath)
os.rmdir (self.name)
except OSError as excp:
log ('error deleting temporary folder "' + self.name + '": ' + excp.strerror)
# error handling helpers:
class VersionError (Exception):
pass
class QMakeError (Exception):
pass
class QMOCError (Exception):
pass
class CompileError (Exception):
pass
class LinkError (Exception):
pass
class RunError (Exception):
pass
def compiler_hint (cmd, flags_var, flags, args_var=None, args=None):
ret='''
Set the '''+ flags_var + ''' environment variable to inform 'configure' of the path to the
''' + cmd + ''' on your system, as follows:
$ export ''' + flags_var + '=' + flags + '''
$./configure
(amend with the actual path to the ''' + cmd + ''' on your system)
'''
if args_var is not None:
ret += '''
If you are using a ''' + cmd + ' other than gcc or clang, you can also set the ' + args_var + '''
environment variable to specify how your ''' + cmd + ''' expects different arguments
to be presented on the command line, for instance as follows:
$ export ''' + args_var + '=' + args + '''
$ ./configure
'''
return ret
def compiler_flags_hint (name, var, flags):
return '''
Set the ''' + var + ''' environment variable to inform 'configure' of
the flags it must provide to the compiler in order to compile
programs that use ''' + name + ''' functionality; this may include the path to
the ''' + name + ''' include files, as well as any required flags.
For example:
$ export ''' + var + '=' + flags + '''
$./configure
(amend with the actual path to the ''' + name + ''' include files on your system)
'''
def linker_flags_hint (name, var, flags):
return '''
Set the ''' + var + ''' environment variable to inform 'configure' of
the flags it must provide to the linker in order to link
programs that use ''' + name + ''' functionality; this may include the path to
the ''' + name + ''' libraries, as well as any required flags.
For example:
$ export ''' + var + '=' + flags + '''
$./configure
(amend with the actual path to the ''' + name + ''' library file on your system)
'''
configure_log_hint='''
See the file 'configure.log' for details. MRtrix3Tissue is a fork of the
MRtrix3 project. The functionality of the configure script is unmodified,
so when experiencing problems with this script, you might be able to find
assistance in the MRtrix3 community forum at http://community.mrtrix.org/.
Make sure to include the full contents of the 'configure.log' file to
enable community members to help you efficiently. If you believe there are
bugs or other issues with the script, it might be useful to flag these to
MRtrix3 developers as well, as bug fixes are likely to be useful to both
MRtrix3 and MRtrix3Tissue.
'''
qt_path_hint='''
Make sure your PATH environment variable includes the location of the correct
version of this command, for example:
$ export PATH=/opt/qt5/bin:$PATH
$./configure
(amend with the actual path to the Qt executables on your system)
'''
def qt_exec_hint (name):
return '''
If your PATH already includes the correct location, but there are several
versions of the command available, use the ''' + name.upper() + ''' environment variable to inform
'configure' of the correct version, for example:
$ export '''+ name.upper() + '=' + name + '''-qt5
$./configure
(amend with the actual name of (or full path to) Qt's ''' + name + ''' on your system)
'''
# other helper functions:
def commit (name, variable):
cache.write (name + ' = ')
if isinstance (variable, list):
cache.write ('[')
if variable:
cache.write(' \'' + '\', \''.join (variable) + '\' ')
cache.write (']\n')
else:
cache.write ('\'' + variable + '\'\n')
def fillin (template, keyvalues):
command_string = []
for item in template:
if item in keyvalues:
if isinstance(keyvalues[item], list):
command_string += keyvalues[item]
else:
command_string += [ keyvalues[item] ]
else:
command_string += [ item ]
return command_string
def execute (cmd, exception, raise_on_non_zero_exit_code = True, cwd = None):
log ('EXEC <<\nCMD: ' + ' '.join(cmd) + '\n')
try:
process = subprocess.Popen (cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=cwd)
( stdout, stderr ) = process.communicate()
log ('EXIT: ' + str(process.returncode) + '\n')
stdout = stdout.decode(errors='ignore').rstrip()
if stdout:
log ('STDOUT:\n' + stdout + '\n')
stderr = stderr.decode(errors='ignore').rstrip()
if stderr:
log ('STDERR:\n' + stderr + '\n')
log ('>>\n\n')
except OSError as e:
log ('error invoking command "' + cmd[0] + '": ' + e.strerror + '\n>>\n\n')
raise exception
except Exception as excp:
error ('unexpected exception of type ' + type(excp).__name__ + ': ' + str(excp) + configure_log_hint)
else:
if raise_on_non_zero_exit_code and process.returncode != 0:
raise exception (stderr)
return (process.returncode, stdout, stderr)
def compile (source, compiler_flags, linker_flags): # pylint: disable=redefined-builtin
global cpp, ld
with TempFile ('.cpp') as srcfile:
log ('\nCOMPILE ' + srcfile.name + ':\n---\n' + source + '\n---\n')
srcfile.fid.write (source)
srcfile.fid.flush()
srcfile.fid.close()
with DeleteAfter (srcfile.name[:-4] + '.o') as objfile:
execute (fillin (cpp, {
'CFLAGS': compiler_flags,
'SRC': srcfile.name,
'OBJECT': objfile.name }), CompileError)
with DeleteAfter ('a.out') as out:
execute (fillin (ld, {
'LDFLAGS': linker_flags,
'OBJECTS': objfile.name,
'EXECUTABLE': out.name }), LinkError)
return execute ([ './'+out.name ], RunError)[1]
#def compare_version (needed, observed):
# needed = [ float(n) for n in needed.split()[0].split('.') ]
# observed = [ float(n) for n in observed.split()[0].split('.') ]
# for n in zip (needed, observed):
# if n[0] > n[1]:
# return False
# return True
def get_flags (default=None, env=None, pkg_config_flags=None):
"""Return a list of the flags required for a given packagei
If 'env' is defined, it will check whether the corresponding environment
variable is set, and if so return its contents. If 'pkg_config_flags' is set,
it will invoke 'pkg-config' with the given arguments, and return its output.
Otherwise it returns the contents of 'default'.
"""
if env:
if env in os.environ.keys():
return shlex.split (os.environ[env])
if pkg_config_flags:
try:
flags = []
for flag in shlex.split (execute ([ 'pkg-config' ] + pkg_config_flags.split(), RunError)[1]):
if flag.startswith ('-I'):
flags += [ '-idirafter', flag[2:] ]
else:
flags += [ flag ]
return flags
except Exception:
log('error running "pkg-config ' + pkg_config_flags + '"\n\n')
return default
def compile_test (name, cflags, ldflags, code, on_success='ok', on_failure='not found'):
"""Tests whether the code given compiles, links, and runs.
This returns True if successful, and False for any type of failure. It will
also report that is it checking for 'name', and print the contents of stdout
if non-empty, or the contents of 'on_success' / 'on_failure' otherwise.
"""
report ('Checking for ' + name + ': ')
try:
stdout = compile (code, cflags, ldflags)
if stdout:
report (stdout.splitlines()[0] + '\n')
else:
report (on_success+'\n')
return True
except Exception:
report (on_failure+'\n')
return False
def compile_check (full_name, name, cflags, ldflags, code, cflags_env=None, cflags_hint=None, ldflags_env=None, ldflags_hint=None, on_success='ok'):
"""Checks whether the code given compiles, links, and runs.
This is intended to check for required dependencies, and will cause
'configure' to abort on failure. It will report that is it checking for
'full_name', and on success print the contents of stdout if non-empty, or the
contents of 'on_success' otherwise. On failure, it will print hints about
what might be going wrong, depending on the specific mode of failure. For
compile and linking errors, the compiler_flags_hint() or linker_flags_hint()
functions will be used to provide helpul hints if the corresponding *_env and
*_hint variables are set. Otherwise, the 'configure_log_hint' message will be
shown. The 'name' variable is a shorthand of the 'full_name' that will be
used during error reporting.
"""
report ('Checking for ' + full_name + ': ')
try:
stdout = compile (code, cflags, ldflags)
if stdout:
report (stdout.splitlines()[0] + '\n')
else:
report (on_success+'\n')
except CompileError:
if cflags_env and cflags_hint:
hint = compiler_flags_hint (name, cflags_env, cflags_hint)
else:
hint = configure_log_hint
error ('error compiling ' + name + ''' application!
MRtrix3Tissue was unable to compile a test program involving ''' + name + '.' + hint)
except LinkError:
if cflags_env and cflags_hint:
hint = linker_flags_hint (name, ldflags_env, ldflags_hint)
else:
hint = configure_log_hint
error ('error linking ' + name + ''' application!
MRtrix3Tissue was unable to link a test program involving ''' + name + '.' + hint)
except RunError:
error ('''runtime error!
Unable to configure ''' + name + configure_log_hint)
except Exception as excp:
error ('unexpected exception of type ' + type(excp).__name__ + ': ' + str(excp) + configure_log_hint)
# OS-dependent variables:
obj_suffix = '.o'
exe_suffix = ''
lib_prefix = 'lib'
ld_lib_flags = []
if system.startswith('mingw') or system.startswith('msys'):
system = 'windows'
report ('Detecting OS: ' + system + '\n')
if system == 'linux':
cpp_flags += [ '-pthread', '-fPIC' ]
lib_suffix = '.so'
ld_flags += [ '-pthread' ]
ld_lib_flags += [ '-shared' ]
runpath = '-Wl,-rpath,$ORIGIN/'
elif system == 'windows':
cxx = [ 'g++', 'clang++' ]
cpp_flags += [ '-pthread', '-DMRTRIX_WINDOWS', '-mms-bitfields', '-Wa,-mbig-obj', '-D_FILE_OFFSET_BITS=64' ]
exe_suffix = '.exe'
lib_prefix = ''
lib_suffix = '.dll'
ld_flags += [ '-pthread', '-Wl,--allow-multiple-definition' ]
ld_lib_flags += [ '-shared' ]
runpath = ''
if debug and not optimlevel: # Compilation will fail otherwise
optimlevel = 1
elif system == 'darwin':
if 'MACOSX_DEPLOYMENT_TARGET' in os.environ and 'QMAKE_MACOSX_DEPLOYMENT_TARGET' in os.environ:
if not os.environ['QMAKE_MACOSX_DEPLOYMENT_TARGET'] == os.environ['MACOSX_DEPLOYMENT_TARGET']:
error ('environment variables QMAKE_MACOSX_DEPLOYMENT_TARGET and MACOSX_DEPLOYMENT_TARGET differ')
macosx_version = os.environ['MACOSX_DEPLOYMENT_TARGET']
elif 'QMAKE_MACOSX_DEPLOYMENT_TARGET' in os.environ:
macosx_version = os.environ['QMAKE_MACOSX_DEPLOYMENT_TARGET']
elif 'MACOSX_DEPLOYMENT_TARGET' in os.environ:
macosx_version = os.environ['MACOSX_DEPLOYMENT_TARGET']
else:
macosx_version = ('.'.join(execute([ 'sw_vers', '-productVersion' ], RunError)[1].split('.')[:2]))
report ('OS X deployment target: ' + macosx_version + '\n')
cpp_flags += [ '-DMRTRIX_MACOSX', '-fPIC', '-mmacosx-version-min='+macosx_version ]
ld_flags += [ '-mmacosx-version-min='+macosx_version ]
ld_lib_flags += [ '-dynamiclib', '-install_name', '@rpath/LIBNAME' ]
runpath = '-Wl,-rpath,@loader_path/'
lib_suffix = '.dylib'
if 'ARCH' in os.environ.keys():
march = os.environ['ARCH']
if march:
report ('Machine architecture set by ARCH environment variable to: ' + march + '\n')
cpp_flags += [ '-march='+march ]
# set CPP compiler:
ld_cmdline = None
if 'CXX' in os.environ.keys():
cxx = shlex.split (os.environ['CXX'])
if 'CXX_ARGS' in os.environ.keys():
cxx_args = shlex.split (os.environ['CXX_ARGS'])
if 'LD' in os.environ.keys():
ld_cmdline = shlex.split (os.environ['LD'])
if 'LD_ARGS' in os.environ.keys():
ld_args = shlex.split (os.environ['LD_ARGS'])
if 'LDLIB_ARGS' in os.environ.keys():
ld_lib_args = shlex.split (os.environ['LDLIB_ARGS'])
# CPP flags:
if 'CFLAGS' in os.environ.keys():
cpp_flags += shlex.split (os.environ['CFLAGS'])
if 'LDFLAGS' in os.environ.keys():
ld_flags += shlex.split (os.environ['LDFLAGS'])
ld_lib_flags += ld_flags
if 'LDLIB_FLAGS' in os.environ.keys():
ld_lib_flags += shlex.split (os.environ['LDLIB_FLAGS'])
for candidate in cxx:
report ('Looking for compiler [' + candidate + ']: ')
cpp = [ candidate ] + cxx_args
if ld_cmdline:
ld = ld_cmdline
else:
ld = copy.copy([ candidate ])
ld_lib = ld + ld_lib_args
ld += ld_args
try:
compiler_version = execute ([ cpp[0], '--version' ], CompileError)[1]
if not compiler_version:
report ('(no version information)\n')
else:
report (compiler_version.splitlines()[0] + '\n')
except Exception:
report ('not found\n')
continue
if compile_test ('C++11 compliance', cpp_flags, ld_flags, '''
#include <cstddef>
struct Base {
Base (int);
};
struct Derived : Base {
using Base::Base;
};
int main() {
Derived D (int); // check for contructor inheritance
return 0;
}
''', on_failure='test failed (see configure.log for details)\n'):
break
else:
error ('''no suitable compiler found!
''' + compiler_hint ('compiler', 'CXX', '/usr/bin/g++-5.5', 'CXX_ARGS', '"-c CFLAGS SRC -o OBJECT"') + configure_log_hint)
# shared library generation:
if not noshared:
report ('Checking shared library generation: ')
with TempFile ('.cpp') as bogus_cpp:
bogus_cpp.fid.write ('int bogus() { return (1); }')
bogus_cpp.fid.flush()
bogus_cpp.fid.close()
with DeleteAfter (bogus_cpp.name[:-4] + '.o') as bogus_obj:
try:
execute (fillin (cpp, {
'CFLAGS': cpp_flags,
'SRC': bogus_cpp.name,
'OBJECT': bogus_obj.name }), CompileError)
except CompileError:
error ('compiler not found!' + configure_log_hint)
except Exception as excp:
error ('unexpected exception of type ' + type(excp).__name__ + ': ' + str(excp) + configure_log_hint)
with DeleteAfter (lib_prefix + 'test' + lib_suffix) as lib:
try:
execute (fillin (ld_lib, {
'LDLIB_FLAGS': ld_lib_flags,
'OBJECTS': bogus_obj.name,
'LIB': lib.name }), LinkError)
except LinkError:
error ('''linker not found!
MRtrix3Tissue was unable to employ the linker program for shared library generation.''' + compiler_hint ('shared library linker', 'LDLIB_FLAGS', '"-L/usr/local/lib"', 'LDLIB_ARGS', '"-shared LDLIB_FLAGS OBJECTS -o LIB"'))
except Exception as excp:
error ('unexpected exception of type ' + type(excp).__name__ + ': ' + str(excp) + configure_log_hint)
report ('ok\n')
report ('Detecting pointer size: ')
try:
pointer_size = int (compile ('''
#include <iostream>
int main() {
std::cout << sizeof(void*);
return (0);
}
''', cpp_flags, ld_flags))
report (str(8*pointer_size) + ' bit\n')
if pointer_size == 8:
cpp_flags += [ '-DMRTRIX_WORD64' ]
elif pointer_size != 4:
error ('unexpected pointer size!')
except Exception as excp:
error ('unexpected exception of type ' + type(excp).__name__ + ': ' + str(excp) + configure_log_hint)
report ('Detecting byte order: ')
if sys.byteorder == 'big':
report ('big-endian\n')
cpp_flags += [ '-DMRTRIX_BYTE_ORDER_IS_BIG_ENDIAN' ]
else:
report ('little-endian\n')
if not compile_test ('variable-length array support', cpp_flags, ld_flags, '''
int main(int argc, char* argv[]) {
int x[argc];
return 0;
}
'''):
cpp_flags += [ '-DMRTRIX_NO_VLA' ]
if not compile_test ('non-POD variable-length array support', cpp_flags, ld_flags, '''
#include <string>
class X {
int x;
double y;
std::string s;
};
int main(int argc, char* argv[]) {
X x[argc];
return 0;
}
'''):
cpp_flags += [ '-DMRTRIX_NO_NON_POD_VLA' ]
if not compile_test ('::max_align_t', cpp_flags, ld_flags, '''
#include <iostream>
#include <cstddef>
using ::max_align_t;
int main() {
std::cout << alignof (max_align_t) << " bytes\\n";
return 0;
}
'''):
cpp_flags += [ '-DMRTRIX_MAX_ALIGN_T_NOT_DEFINED' ]
if not compile_test ('std::max_align_t', cpp_flags, ld_flags, '''
#include <iostream>
#include <cstddef>
using std::max_align_t;
int main() {
std::cout << alignof (max_align_t) << " bytes\\n";
return 0;
}
'''):
cpp_flags += [ '-DMRTRIX_STD_MAX_ALIGN_T_NOT_DEFINED' ]
# Eigen3 flags:
eigen_cflags = get_flags ([ '-isystem', '/usr/include/eigen3' ], 'EIGEN_CFLAGS', '--cflags eigen3')
compile_check ('Eigen3 library', 'Eigen3', cpp_flags + eigen_cflags, ld_flags, '''
#include <cstddef>
#include <Eigen/Core>
#include <iostream>
int main (int argc, char* argv[]) {
std::cout << EIGEN_WORLD_VERSION << "." << EIGEN_MAJOR_VERSION << "." << EIGEN_MINOR_VERSION << "\\n";
return 0;
}
''', 'EIGEN_CFLAGS', '"-isystem /usr/include/eigen3"')
if not openmp:
eigen_cflags += [ '-DEIGEN_DONT_PARALLELIZE' ]
# zlib:
zlib_cflags = get_flags ([], 'ZLIB_CFLAGS', '--cflags zlib')
zlib_ldflags = get_flags ([ '-lz' ], 'ZLIB_LDFLAGS', '--libs zlib')
compile_check ('zlib compression library', 'zlib', cpp_flags + zlib_cflags, ld_flags + zlib_ldflags, '''
#include <iostream>
#include <zlib.h>
int main() {
std::cout << zlibVersion();
return (0);
}
''', 'ZLIB_CFLAGS', '"-isystem /usr/local/include"', 'ZLIB_LDFLAGS', '"-L/usr/local/lib -lz"')
cpp_flags += zlib_cflags
ld_flags += zlib_ldflags
ld_lib_flags += zlib_ldflags
# Test that JSON for Modern C++ will compile, since it enforces its own requirements
compile_check ('"JSON for Modern C++" requirements', 'JSON for modern C++', \
cpp_flags + [ '-I'+os.path.abspath(os.path.join(os.path.dirname(sys.argv[0]), 'core')) ], ld_flags, '''
#include "''' + os.path.join('file', 'json.h') + '''"
int main (int argc, char* argv[])
{
nlohmann::json json;
json["key"] = "value";
}
''')
# TIFF:
tiff_cflags = get_flags ([], 'TIFF_CFLAGS', '--cflags libtiff-4')
tiff_ldflags = get_flags ([ '-ltiff' ], 'TIFF_LDFLAGS', '--libs libtiff-4')
if compile_test ('TIFF library', cpp_flags + tiff_cflags, ld_flags + tiff_ldflags, '''
#include <iostream>
#include <tiffio.h>
int main() {
std::cout << TIFFGetVersion();
return (0);
}
''', on_failure='not found - TIFF support disabled'):
cpp_flags += [ '-DMRTRIX_TIFF_SUPPORT' ] + tiff_cflags
ld_flags += tiff_ldflags
ld_lib_flags += tiff_ldflags
# PNG:
png_cflags = get_flags ([], 'PNG_CFLAGS', '--cflags libpng')
png_ldflags = get_flags ([ '-lpng' ], 'PNG_LDFLAGS', '--libs libpng')
if compile_test ('PNG library', cpp_flags + png_cflags, ld_flags + png_ldflags, '''