Skip to content

Commit 3692ea2

Browse files
Apply suggestions from code review
Co-authored-by: Jonatan Kłosko <jonatanklosko@gmail.com>
1 parent cf9b01d commit 3692ea2

File tree

3 files changed

+32
-20
lines changed

3 files changed

+32
-20
lines changed

example/Makefile

Lines changed: 23 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,29 @@
1-
SRC := c_src/example_nif.cpp
2-
TARGET := $(MIX_BUILD_DIR)/example_nif.so
1+
PRIV_DIR := $(MIX_APP_PATH)/priv
2+
NIF_PATH := $(PRIV_DIR)/libexample.so
3+
C_SRC := $(shell pwd)/c_src
34

4-
CPPFLAGS := -std=c++17 -fvisibility=hidden -fPIC -I$(ERL_INCLUDE_DIR) -I$(FINE_INCLUDE_DIR)
5+
CPPFLAGS := -shared -fPIC -std=c++17 -Wall -Wextra
6+
CPPFLAGS += -I$(ERTS_INCLUDE_DIR) -I$(FINE_INCLUDE_DIR)
57

6-
ifeq ($(shell uname -s),Darwin)
7-
LDFLAGS := -dynamiclib -undefined dynamic_lookup
8+
ifdef DEBUG
9+
CPPFLAGS += -g
810
else
9-
LDFLAGS := -shared
11+
CPPFLAGS += -O3
1012
endif
1113

12-
all: $(TARGET)
14+
ifndef TARGET_ABI
15+
TARGET_ABI := $(shell uname -s | tr '[:upper:]' '[:lower:]')
16+
endif
17+
18+
ifeq ($(TARGET_ABI),darwin)
19+
CPPFLAGS += -undefined dynamic_lookup -flat_namespace
20+
endif
21+
22+
SOURCES := $(wildcard $(C_SRC)/*.cpp)
23+
24+
all: $(NIF_PATH)
25+
@ echo > /dev/null # Dummy command to avoid the default output "Nothing to be done"
1326

14-
$(TARGET): $(SRC)
15-
$(CXX) $(CPPFLAGS) $(LDFLAGS) -o $@ $^
27+
$(NIF_PATH): $(SOURCES)
28+
@ mkdir -p $(PRIV_DIR)
29+
$(CXX) $(CPPFLAGS) $(SOURCES) -o $(NIF_PATH)

example/lib/example.ex

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,13 @@
11
defmodule Example do
2-
@on_load :load_nif
3-
@mix_build_dir Mix.Project.build_path()
2+
@on_load :__on_load__
43

5-
defp load_nif do
6-
:erlang.load_nif(~c"#{@mix_build_dir}/example_nif", 0)
4+
def __on_load__ do
5+
path = :filename.join(:code.priv_dir(:example), ~c"libexample")
6+
7+
case :erlang.load_nif(path, 0) do
8+
:ok -> :ok
9+
{:error, reason} -> raise "failed to load NIF library, reason: #{inspect(reason)}"
10+
end
711
end
812

913
@doc """

example/mix.exs

Lines changed: 1 addition & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -7,13 +7,7 @@ defmodule Example.MixProject do
77
version: "0.1.0",
88
elixir: "~> 1.15",
99
compilers: [:elixir_make] ++ Mix.compilers(),
10-
make_env: fn ->
11-
%{
12-
"MIX_BUILD_DIR" => Mix.Project.build_path(),
13-
"ERL_INCLUDE_DIR" => "#{:code.root_dir()}/usr/include",
14-
"FINE_INCLUDE_DIR" => Fine.include_dir()
15-
}
16-
end,
10+
make_env: fn -> %{"FINE_INCLUDE_DIR" => Fine.include_dir()} end,
1711
deps: deps()
1812
]
1913
end

0 commit comments

Comments
 (0)