【问题标题】:Using rakefile to compile C files使用 rakefile 编译 C 文件
【发布时间】:2019-06-01 06:08:57
【问题描述】:

我在使用 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)

【问题讨论】:

    标签: ruby rake rakefile cflags


    【解决方案1】:

    TEST_CONST="\'A STRING\'" 可以工作。

    它会导致:

    sh "gcc -c #{task.source} -DVAR=#{TEST_CONST}"
    

    内插到:

    gcc -c test.c -DVAR='A STRING'
    

    【讨论】:

    • 你说得对,它在编译时是如何体现的。但我仍然遇到 rake 中止失败。
    • 这应该是诱导的。我复制粘贴了你的 sn-ps 并确保它编译并成功运行。
    • 我已经更新了帖子。我有点惊讶它对你有用,可能是我缺少一些 Ruby 依赖项左右。您是在 Windows 上运行,还是在 Windows 上运行?
    • 不,我在 Linux 上。
    • 这对我有用:TEST_CONST='\""A STRING"\"'。也许,它与 GCC 版本有关,我的 ist 7.3.0
    猜你喜欢
    • 1970-01-01
    • 2012-01-05
    • 2021-06-03
    • 1970-01-01
    • 2012-12-02
    • 2011-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多