| 1 |
#!/usr/bin/env python3 |
| 2 |
|
| 3 |
import shutil, sys, subprocess, argparse, pathlib |
| 4 |
import platform |
| 5 |
|
| 6 |
parser = argparse.ArgumentParser() |
| 7 |
|
| 8 |
parser.add_argument('--private-dir', required=True) |
| 9 |
parser.add_argument('-o', required=True) |
| 10 |
parser.add_argument('cmparr', nargs='+') |
| 11 |
|
| 12 |
contents = '''#include<stdio.h> |
| 13 |
|
| 14 |
void flob(void) { |
| 15 |
printf("Now flobbing.\\n"); |
| 16 |
} |
| 17 |
''' |
| 18 |
|
| 19 |
def get_pic_args(): |
| 20 |
platname = platform.system().lower() |
| 21 |
if platname in ['windows', 'darwin'] or sys.platform == 'cygwin': |
| 22 |
return [] |
| 23 |
return ['-fPIC'] |
| 24 |
|
| 25 |
def generate_lib_gnulike(outfile, c_file, private_dir, compiler_array): |
| 26 |
if shutil.which('ar'): |
| 27 |
static_linker = 'ar' |
| 28 |
elif shutil.which('llvm-ar'): |
| 29 |
static_linker = 'llvm-ar' |
| 30 |
elif shutil.which('gcc-ar'): |
| 31 |
static_linker = 'gcc-ar' |
| 32 |
else: |
| 33 |
sys.exit('Could not detect a static linker.') |
| 34 |
o_file = c_file.with_suffix('.o') |
| 35 |
compile_cmd = compiler_array + ['-c', '-g', '-O2', '-o', str(o_file), str(c_file)] |
| 36 |
compile_cmd += get_pic_args() |
| 37 |
subprocess.check_call(compile_cmd) |
| 38 |
out_file = pathlib.Path(outfile) |
| 39 |
if out_file.exists(): |
| 40 |
out_file.unlink() |
| 41 |
link_cmd = [static_linker, 'csr', outfile, str(o_file)] |
| 42 |
subprocess.check_call(link_cmd) |
| 43 |
return 0 |
| 44 |
|
| 45 |
|
| 46 |
def generate_lib_msvc(outfile, c_file, private_dir, compiler_array): |
| 47 |
static_linker = 'lib' |
| 48 |
o_file = c_file.with_suffix('.obj') |
| 49 |
compile_cmd = compiler_array + ['/MDd', |
| 50 |
'/nologo', |
| 51 |
'/ZI', |
| 52 |
'/Ob0', |
| 53 |
'/Od', |
| 54 |
'/c', |
| 55 |
'/Fo' + str(o_file), |
| 56 |
str(c_file)] |
| 57 |
subprocess.check_call(compile_cmd) |
| 58 |
out_file = pathlib.Path(outfile) |
| 59 |
if out_file.exists(): |
| 60 |
out_file.unlink() |
| 61 |
link_cmd = [static_linker, |
| 62 |
'/nologo', |
| 63 |
'/OUT:' + str(outfile), |
| 64 |
str(o_file)] |
| 65 |
subprocess.check_call(link_cmd) |
| 66 |
return 0 |
| 67 |
|
| 68 |
def generate_lib(outfile, private_dir, compiler_array): |
| 69 |
private_dir = pathlib.Path(private_dir) |
| 70 |
if not private_dir.exists(): |
| 71 |
private_dir.mkdir() |
| 72 |
c_file = private_dir / 'flob.c' |
| 73 |
c_file.write_text(contents, encoding='utf-8') |
| 74 |
for i in compiler_array: |
| 75 |
if (i.endswith('cl') or i.endswith('cl.exe')) and 'clang-cl' not in i: |
| 76 |
return generate_lib_msvc(outfile, c_file, private_dir, compiler_array) |
| 77 |
return generate_lib_gnulike(outfile, c_file, private_dir, compiler_array) |
| 78 |
|
| 79 |
if __name__ == '__main__': |
| 80 |
options = parser.parse_args() |
| 81 |
sys.exit(generate_lib(options.o, options.private_dir, options.cmparr)) |