不在命令行上使用预处理器值进行编译
我哪里错了;我想在命令行上为 g++ 定义一个预处理器值,但失败了。下面是复制我的问题的示例代码:
[edit] 我正在使用:
g++ (Debian 4.3.2-1.1) 4.3.2
GNU Make 3.81
test.h
#ifndef _test_h_
#define _test_h_
#include "iostream"
#if defined(MY_DEFINED_VALUE)
#if (MY_DEFINED_VALUE != 5)
#undef MY_DEFINED_VALUE
#define MY_DEFINED_VALUE 3
#endif //(MY_DEFINED_VALUE != 5)
#else //defined(MY_DEFINED_VALUE)
#error Error - MY_DEFINED_VALUE is not defined
#endif //defined(MY_DEFINED_VALUE)
class test
{
public:
int val;
test() {}
void show() { std::cout << "val = " << val << "\n"; }
};
#endif //_test_h_
test.cpp
//#define MY_DEFINED_VALUE 5
#include "test.h"
int main()
{
test t;
t.val = MY_DEFINED_VALUE;
t.show();
return 0;
}
Makefile
#=====
CC = g++
LD = g++
USERDEFINES = -DMY_DEFINED_VALUE
CFLAGS = -Wall
LDFLAGS =
RM = /bin/rm -f
SRCS = test.cpp
OBJS = test.o
PROG = test
#=====
$(PROG): $(OBJS)
$(LD) $(LDFLAGS) $(OBJS) -o $(PROG)
#=====
%.o: %.c
$(CC) $(USERDEFINES) $(CFLAGS) -c $<
#=====
clean:
$(RM) $(PROG) $(OBJS)
如果我取消注释 < test.cpp 中的 code>#define 一切正常(打印 5)。如果我评论它,我会收到#error
。
Where am I going wrong; I want to define a preprocessor value on the command-line for g++ but it fails. Below is sample code that replicate my problem:
[edit] I'm using:
g++ (Debian 4.3.2-1.1) 4.3.2
GNU Make 3.81
test.h
#ifndef _test_h_
#define _test_h_
#include "iostream"
#if defined(MY_DEFINED_VALUE)
#if (MY_DEFINED_VALUE != 5)
#undef MY_DEFINED_VALUE
#define MY_DEFINED_VALUE 3
#endif //(MY_DEFINED_VALUE != 5)
#else //defined(MY_DEFINED_VALUE)
#error Error - MY_DEFINED_VALUE is not defined
#endif //defined(MY_DEFINED_VALUE)
class test
{
public:
int val;
test() {}
void show() { std::cout << "val = " << val << "\n"; }
};
#endif //_test_h_
test.cpp
//#define MY_DEFINED_VALUE 5
#include "test.h"
int main()
{
test t;
t.val = MY_DEFINED_VALUE;
t.show();
return 0;
}
Makefile
#=====
CC = g++
LD = g++
USERDEFINES = -DMY_DEFINED_VALUE
CFLAGS = -Wall
LDFLAGS =
RM = /bin/rm -f
SRCS = test.cpp
OBJS = test.o
PROG = test
#=====
$(PROG): $(OBJS)
$(LD) $(LDFLAGS) $(OBJS) -o $(PROG)
#=====
%.o: %.c
$(CC) $(USERDEFINES) $(CFLAGS) -c lt;
#=====
clean:
$(RM) $(PROG) $(OBJS)
If I uncomment the #define
in test.cpp, all is well (prints 5). If I comment it I get the #error
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
问题出在你的 Makefile 中。
%.o: %.c
规则与 .cpp 文件不匹配,因此会触发 GNU Make 的内置%.o: %.cpp
规则。如果将
%.o: %.c
更改为%.o: %.cpp
,它将运行良好。The problem is in your Makefile. The
%.o: %.c
rule doesn't match a .cpp file, so GNU Make's built-in%.o: %.cpp
rule is being triggered instead.If you change
%.o: %.c
to%.o: %.cpp
, it'll run fine.