【问题标题】:Using G++ to compile multiple *.cpp and *.h files in Sublime 2在 Sublime 2 中使用 G++ 编译多个 *.cpp 和 *.h 文件
【发布时间】:2014-03-24 06:23:11
【问题描述】:

在 MAC 上,我可以使用命令行成功编译 c++ 程序

  g++ *.cpp *.h -o executablename

但是它在 Sublime 2 中失败了——我为此创建了一个构建系统

 {
 "cmd" : ["g++", "*.cpp", "*.h", "-o", "executablename"]
 }

有了这些结果

 i686-apple-darwin11-llvm-g++-4.2: *.cpp: No such file or directory
 i686-apple-darwin11-llvm-g++-4.2: *.h: No such file or directory
 i686-apple-darwin11-llvm-g++-4.2: no input files
 [Finished in 0.0s with exit code 1]

但是,如果我在项目中创建具有特定文件名的构建系统,它就可以工作:

{
"cmd" : ["g++", "Test.cpp", "TestCode.cpp", "TestCode.h", "TestCode2.cpp", "TestCode2.h", "-o", "executablename"]
}

如何在 Sublime 2 中创建使用命令行模式编译多个文件的构建系统,就像在命令行上一样?

【问题讨论】:

  • 你永远不会直接编译.h 文件。当它们在.cpp 文件中为#included 时,它们会根据需要进行编译。所以至少删除*.h
  • 在Sublime Text中使用*.cpp失败的原因是,gcc没有做通配符扩展。当您使用通配符从命令行运行 gcc 时,shell 会扩展它们并为 gcc 提供文件名列表。所以你需要了解如何在 Sublime Text 中做等效(通过通配符或其他类似方法获取文件名)。
  • 另外说明一下,直接调用编译器是非常的,这个怎么放,原始方式来构建软件。通常使用 makefile 或其他更高级的方法。
  • 让一个 c++ 从 Sublime 2 构建和运行一直是一个挑战,只是让它工作。如果有人对更好的方法有建议,我将不胜感激。

标签: c++ g++ sublimetext2 build-system


【解决方案1】:

谢谢海德。

根据您的建议使用构建系统后,这可行:

{
"cmd" : ["g++ *.cpp -o executablename"],
"shell":true
}

【讨论】:

  • 使用"cmd": ["g++ *.cpp -o test && gnome-terminal -- './test'"](或等效的终端程序,如 konsole 或 xterm 代替 gnome-terminal)然后运行它。我使用的是gnome-terminal -x sh -c './test',但后来它说只需使用-- 来终止选项并在之后输入命令。
【解决方案2】:

你也许应该使用这样的东西:

{
 "cmd" : ["gmake"]
}

或者可能只是make 而不是gmake。但是如果你有gcc,GNU make 应该在同一个目录中。下面的示例 Makefile 是用 GNU Make 测试的,如果不进行其他地方的小修改,它可能无法工作。

所以这里有一个非常原始的 Makefile 供您使用。重要的!它应该被命名为 Makefile 以便 GNU Make 会在没有参数的情况下找到它,并且在其中您必须使用实际的制表符字符进行缩进(在 g++rm 命令)。

CXXFLAGS := -Wall -Wextra $(CXXFLAGS) # example of setting compilation flags

# first rule is default rule, commonly called 'all'
# if there many executables, you could list them all
all: executablename

# we take advantage of predefined "magic" rule to create .o files from .cpp

# a rule for linking .o files to executable, using g++ to get C++ libs right 
executablename: TestCode.o TestCode2.o Test.o
    g++ $^ -o $@

# $^ means all dependencies (the .o files in above rule)
# $@ means the target (executablename in above rule)

# rule to delete generated files, - at start means error is ignored
clean:
    -rm executablename *.o

但如今,即使使用手写的 Makefile 也被认为是原始的。您或许应该安装并学习使用CMake

【讨论】:

    猜你喜欢
    • 2011-03-13
    • 2015-01-05
    • 1970-01-01
    • 1970-01-01
    • 2018-03-10
    • 1970-01-01
    • 1970-01-01
    • 2012-01-31
    相关资源
    最近更新 更多