我有这段代码:
eng_cppheader = function(options)
{
opts = options$engine.opts
code = paste(options$code, collapse = "\n")
if (is.null(opts$path)) opts$path = tempdir()
cat(code, file = file.path(opts$path, opts$filename))
Sys.setenv(PKG_CPPFLAGS = paste0("-I", opts$path))
options$engine = 'cpp'
engine_output(options, code, "")
}
knitr::knit_engines$set(cppheader=eng_cppheader)
如果我调用它,即使eval = FALSE,我也会得到:
/ bin / sh:cppheader:找不到命令
我已经尝试了
{r,engine =" cppheader",...} 和 {cppheader,...}
似乎注册新引擎会自动调用eng_interpreted。有没有办法设置它而没有系统调用?
更新:
我得到它编织,但它在作为笔记本运行时崩溃了RStudio。此外,没有" engine.opts" "选项"中的字段名单。我不得不改变它。
这是Rmd。编织得很好。
---
title: "C++ Header Engine Demo"
output:
html_document:
df_print: paged
html_notebook: default
pdf_document: default
---
```{r}
eng_cppheader = function(options)
{
code = paste(options$code, collapse = "\n")
if (is.null(options$file) || nzchar(options$file) == 0)
stop("file is a required chunk options")
if (is.null(options$path)) options$path = tempdir()
cat(code, file = file.path(options$path, options$file))
Sys.setenv(PKG_CPPFLAGS = paste0("-I\"", options$path, "\""))
options$engine = 'cpp'
knitr::engine_output(options, code, "")
}
knitr::knit_engines$set(cppheader=eng_cppheader)
```
```{r}
names(knitr::knit_engines$get())
```
```{r}
knitr::knit_engines$get()$cppheader(
list(code="Hello world!",
echo=T, prompt=T, highlight=T,
file = "test.h"))
```
```{r}
system2('cat', file.path(tempdir(), "test.h"), stdout = TRUE)
```
```{r}
unlink(file.path(tempdir(), "test.h"))
```
```{cppheader, file="test.h"}
#ifndef __test_h__
#define __test_h__
#define test_string "Hello world!"
#include <string>
using std::string;
#endif // __test_h__
```
```{r}
header_file = file.path(tempdir(), "test.h")
ifelse(file.exists(header_file), "I found it!", "I did not find it!")
```
```{r}
Sys.getenv("PKG_CPPFLAGS")
```
```{Rcpp}
#include "test.h"
// [[Rcpp::export]]
string test_it()
{
return test_string;
}
```
```{r}
print(try(test_it()))
```