C++链接和编译标志
问题描述:
我可能有一个愚蠢的问题,但没有问题是愚蠢的我会问它...让我们想象我有文件matrix.hpp
和matrix.cpp
。在这些文件中,我使用assert(...)
来确保某些条件得到尊重。我编译这个文件并得到一个matrix.o
文件。现在,我将在许多不同的程序中使用这个matrix.o
文件,其中一些只是测试,需要检查assert(...)
条件,而其他人正在运行的程序不需要这些检查。C++链接和编译标志
我的问题是:我可以编译matrix.o
没有-DNDEBUG
标志,因此通常情况下,assert(...)
条件将被检查。但是当我链接不需要检查的程序的.o文件时,我添加了这个标志而没有重新编译matrix.o
文件。
更确切地说,这会做我想做:
# the test program with the "assert(..)" checks
test:test.o matrix.o
gcc -o [email protected] $^
test.o:test.cpp matrix.hpp
gcc -c $^
# the real program without the "assert(..)" checks
prog:prog.o matrix.o
gcc -o [email protected] $^ -DNDEBUG
prog.o:prog.cpp matrix.hpp
gcc -c -DNDEBUG $^
# the matrix.o that can be either checked or not if the -DNDEBUG flag
# is given when the .o files are linked
matrix.o:matrix.cpp matrix.hpp
gcc -c $^
好的,谢谢您的回答!所以我不能简单地使用标志-DNDEBUG。如果有什么我的每个矩阵中的文件使用“断言(......)”一次,我补充一下:
#ifdef CHECK
assert(...)
#endif
,现在当我编制了“试验”方案我使用检查标记,但不与“编程”程序?我想这也行不通...
答
不,与GCC无关。我看到两个选项:
- 编译
matrix.o
两个版本,并链接相应的版本为每个程序,或 - 与手动检查抛出异常代替
assert
。
即使在非测试程序中,后面的选项显然有一些运行时成本,所以小心使用它(不在内部循环中)。
我认为两个相关的问题是相关的:http://stackoverflow.com/questions/8035394/gnu-make-how-to-make-conditional-cflags 其中引用http://stackoverflow.com/questions/ 5127977/makefile-define-compilation-variables-based-on-target-for/5153406#5153406 –