Use Python to help cross-compiling
When porting some software package to embedded environment. There may be an obstacle introduced by makefile, that is, the source code is organized in hierarchical tree. And to make things worsen, you cannot overwrite the environment by using -e option of make or through shell environment variables. Usually, we can work around this problem by shell and sed and awk. But, as we all know, shell script language is so obsecure. However, on the other hand, python is so elegant and neat. Well, what I want to state here is that python maybe a good choice for this situation. To prove this viewpoint, in this short essay, I'll resort to python sticked with sed to realize the same feature as shell scripts. First let me state the problem: I have a software package which is coordinated to X86 architecture. But now I'll have to port it to uCLinux running on BlackFin561. The Makefile of that software is so awkward and boring. It's recursed in every subdirectory. And I cannot overwrite the Makefile's environment variables, since the variables are not just defined in toplevel Makefile -- they are defined in every sub Makefile repeatly. To solve this trouble, I decided to change them to the cross toolchain for BlackFin561 -- which are, bfin-uclinux-gcc, bfin-uclinux-ranlib, et. al. Thus, there comes following python code. This short piece of python code maybe not very useful, but it indeed is useful for me -- The cross compiling work finished well.
#!/bin/env python
import string
import glob
import os
def main():
iter(".")
pass
def iter(dir):
file_items = os.listdir(dir)
for item in file_items:
path = os.path.join(dir, item)
if os.path.isdir(path):
iter(path)
if item == "Makefile" or item[-4:] == ".mak":
file_path = os.path.join(dir, item)
tmp_file_path = os.path.join(dir, "makefile")
command = "sed s/-march=pentium//g " + file_path + " > " + tmp_file_path
os.system(command)
os.rename(tmp_file_path, file_path)
command = "sed s/-march=bf561//g " + file_path + " > " + tmp_file_path
os.system(command)
os.rename(tmp_file_path, file_path)
command = "sed s/-mcpu=pentium/-mcpu=bf561/g " + file_path + " > " + tmp_file_path
os.system(command)
os.rename(tmp_file_path, file_path)
command = "sed s/CC=gcc/CC=bfin-uclinux-gcc/g " + file_path + " > " + tmp_file_path
os.system(command)
os.rename(tmp_file_path, file_path)
command = "sed s/CXX=g++/CXX=bfin-uclinux-g++/g " + file_path + " > " + tmp_file_path
os.system(command)
os.rename(tmp_file_path, file_path)
command = "sed s/RANLIB=ranlib/RANLIB=bfin-uclinux-ranlib/g " + \
file_path + " > " + tmp_file_path
os.system(command)
os.rename(tmp_file_path, file_path)
if __name__ == "__main__":
main()