我在使用 rake 编译 C 文件时遇到问题。我可以在 rakefile 中定义我的常量,并在我的 C 文件中打印出这个常量的值。
当定义的常量是整数时,这工作正常,可以按预期编译、链接和执行。但是,当一个字符串在 rake 文件中定义为常量时,我无法编译。我确定我在这里缺少正确的语法。
这是我的rakefile.rb
require 'rake/clean'
CLEAN.include('*.o')
CLOBBER.include('*.exe')
source_files = Rake::FileList["*.c"]
object_files = source_files.ext(".o")
TEST_CONST="A STRING" #### <---- This causes problem
task :default => "test_app"
task :clean do
sh "rm -rfv *.o"
end
desc "Build the binary executable"
file "test_app" => object_files do |task|
sh "gcc #{object_files} -o #{task.name}"
end
rule '.o' => '.c' do |task|
sh "gcc -c #{task.source} -DVAR=#{TEST_CONST}"
end
这是我的 C 文件:
#include <stdio.h>
int main () {
printf("Running main\n");
printf("VAR: %s\n",VAR);
}
这是错误日志:
<command-line>:0:5: error: ‘A STRING’ undeclared (first use in this function)
main.c:6:24: note: in expansion of macro ‘VAR’
printf("VAR: %s\n",VAR);
^~~
<command-line>:0:5: note: each undeclared identifier is reported only once for each function it appears in
main.c:6:24: note: in expansion of macro ‘VAR’
printf("VAR: %s\n",VAR);
^~~
rake aborted!
在 makefile 中,我会向 CFLAGS 添加类似这样的内容:-DSTRVAR=\"$(VAR)\"
我不知道如何使用 rake 来执行此操作,即将字符串常量作为编译标志传递。有没有人遇到过这个特定的问题,并且可以提供一些想法?
编辑1:
我按照建议将分配更改TEST_CONST="'(A STRING)'"
为,这是我得到的错误,我在 Ubuntu Linux 上运行。
gcc -c main.c -DVAR='A STRING'
main.c: In function ‘main’:
<command-line>:0:5: error: ‘A’ undeclared (first use in this function)
main.c:10:25: note: in expansion of macro ‘VAR’
printf("VAR: %s \n",VAR);
^~~
<command-line>:0:5: note: each undeclared identifier is reported only once for each function it appears in
main.c:10:25: note: in expansion of macro ‘VAR’
printf("VAR: %s \n",VAR);
^~~
<command-line>:0:7: error: expected ‘)’ before ‘STRING’
main.c:10:25: note: in expansion of macro ‘VAR’
printf("VAR: %s \n",VAR);
^~~
rake aborted!
Command failed with status (1): [gcc -c main.c -DVAR='A STRING'...]
/home/abel/Projects/rake_test/rakefile.rb:23:in `block in <top (required)>'
Tasks: TOP => default => test_app => main.o
(See full trace by running task with --trace)