Python:代替gcc/g++ -o filename file 命令行 。

经常练习C语言,所有有许多的源代码需要编译。但是每次都要用到 -o 加上文件名,比较麻烦,所有用python编了一个程序完成整体的操作,不需要 -o filename 部分,可以使用 -g参数。这个程序还不能支持多文件编译。这个功能会不久后加上。

#!/usr/bin/env python
"""
File: gg.py
-----------------
create single/multi c/c++ source file(s)
the output has the same name with the source file
so you can compile c/c++ source file without -o
"""
import os
import sys
import getopt


def my_compile(filepath):
    if not os.path.isfile(filepath):
        print "the source file does not exists!"
        sys.exit(2)
    file_ext=filepath.rpartition(".")[2]
    cmd=filepath.rpartition(".")[0]
    if file_ext=='c':
        os.system("gcc -g -o %s %s && %s" % (cmd, filepath, cmd))
    if file_ext in ('C', 'cpp'):
        os.system("g++ -g -o %s %s && %s" % (cmd, filepath, cmd))

def _usage():
    print "usage: ", "[-g] filename"
    sys.exit(2) 

def main():
    try:
        opts, args=getopt.getopt(sys.argv[1:], 'h')
    except getopt.GetoptError, err:
        sys.stderr=err
        _useage()

    # check opts
    for opt in opts:
        if '-h' in opt:
            _usage() 
    # check args
    filepath=args[0]
    if os.path.dirname(filepath) is '':
        filepath=os.path.join("./", filepath)
    my_compile(filepath) # file will be checked in my_compile function

if __name__=='__main__':
    main()

原文链接: https://www.cnblogs.com/nathaninchina/archive/2012/04/06/python_c_compile.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/46287

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月8日 下午10:40
下一篇 2023年2月8日 下午10:41

相关推荐